Batch多语句操作
在一次任务中,执行多条数据
Statement实现
Connection conn = null;
Statement stmt = null;
try {
conn = DBUtil.getConnection();
stmt = conn.createStatement();
stmt.addBatch("insert into test_jdbc (id,name,money) values(21,'stmt多条测试1',99.12)");
stmt.addBatch("insert into test_jdbc (id,name,money) values(22,'stmt多条测试2',99.22)");
stmt.addBatch("insert into test_jdbc (id,name,money) values(23,'stmt多条测试3',99.32)");
stmt.addBatch("insert into test_jdbc (id,name,money) values(24,'stmt多条测试4',99.42)");
stmt.executeBatch();
System.out.println("执行成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.close(stmt);
DBUtil.close(conn);
}
PreparedStatement实现
Connection conn = null;
PreparedStatement prst = null;
try {
conn = DBUtil.getConnection();
String sql = "insert into test_jdbc (id,name,money) values(?,?,?)";
prst = conn.prepareStatement(sql);
prst.setInt(1, 31);
prst.setString(2, "prst多条测试1");
prst.setDouble(3, 11.1);
prst.addBatch();
prst.setInt(1, 32);
prst.setString(2, "prst多条测试2");
prst.setDouble(3, 21.1);
prst.addBatch();
prst.setInt(1, 33);
prst.setString(2, "prst多条测试3");
prst.setDouble(3, 31.1);
prst.addBatch();
prst.executeBatch();
System.out.println("执行成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.close(prst);
DBUtil.close(conn);
}