引言
当需要成批插入或者更新记录时,可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率
JDBC的批量处理语句包括下面三个方法:
- addBatch(String):添加需要批量处理的SQL语句或是参数;
- executeBatch():执行批量处理语句;
- clearBatch():清空缓存的数据
通常我们会遇到两种批量执行SQL语句的情况:
- 多条SQL语句的批量处理;
- 一个SQL语句的批量传参;
高效的批量插入
举例,创建表插入5000条数据
创建student表,创建如下:
CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20)
);
层次1.使用Statement
Statement st = conn.createStatement();
for(int i = 1;i <= 20000;i++){
String sql = "insert into goods(name) values('name_' + "+ i +")";
st.executeUpdate(sql);
}
statement有sql注入问题,开发中也不会使用,所以简单叙述一下直接跳过
层次2.使用PreparedStatement
public void test(){
Connection con=null;
PreparedStatement pre=null;
try {
//加载注册驱动
Class.forName("com.mysql.jdbc.Driver");
//建立连接
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
//创建PreparedStatement
String sql="insert into student(name) value(?);";
pre = con.prepareStatement(sql);
for(int i=1