jdbc批处理进行多条数据插入

时间:2023-03-09 21:34:11
jdbc批处理进行多条数据插入
package cn.linjun.demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement; public class DemoBrach { private static Connection connection;
private static Statement statement; public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "root");
connection.setAutoCommit(false);
statement = connection.createStatement();
for (int i=1;i<100;i++){ //同时插入100条数据
statement.addBatch("insert into user1 values (null,'lideng"+i+"',20000)"); }
statement.executeBatch();
connection.commit();
} catch (Exception e) {
e.printStackTrace();
}finally {
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} }
}