jdbc包含batch功能,使用executeBatch方法实现批量操作。
void jdbc() throws Exception{
Connection conn = null;
PreparedStatement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
statement = conn.prepareStatement("insert into coures(id,name,age) values(?,?,?)");
conn.setSavepoint();
conn.setAutoCommit(false);
for(int i=0;i<100;i++){
statement.setInt(1, i);
statement.setString(2, "tch");
statement.setInt(3, 23);
statement.addBatch();
}
statement.executeBatch();
conn.commit();
} catch (Exception e) {
if(conn != null){
conn.rollback();
}
e.printStackTrace();
}finally{
if(statement != null){
statement.close();
}
if(conn != null){
conn.close();
}
}
}
代码片段:
1.使用Statement
Connection conn = ConnectDBUtil.getConnection(); //从自己写的工具类获取Connection
conn.setAutoCommit(false); //设定自动提交为false
Statement batchStat = conn.createStatement(); //创建Statement
for(int i=0 ; i<10000 ; i++){
String sql = "insert into test(id,name) values(" + i + ",'Jason')";
batchStat.addBatch(insert); //这里将sql语句加到batch里面
}
batchStat.executeBatch(); //执行batch,将batch里面的sql发到数据库
conn.commit();
2.使用PreparedStatement
Connection conn = ConnectDBUtil.getConnection(); //从自己写的工具类获取Connection
conn.setAutoCommit(false); //设定自动提交为false
PreparedStatement batchStat =
conn_manager.prepareStatement("insert into test(id,name) values(?,?)");
for(int i=0 ; i<10000 ; i++){
batchStat.setInt(1,i);
batchStat.setString(2,"Jason");
batchStat.addBatch();
}
batchStat.executeBatch(); //执行batch,将batch里面的sql发到数据库
conn.commit();