jdbc批处理
批处理,一次操作中执行多条SQL语句,比一条条挨个处理效率高很多
Statement 批处理
Statement
不能使用占位符填充参数,可能有SQL注入风险- 可以同时执行多条
DELETE
UPDATE
INSERT
语句
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "root", "root");
Statement statement = connection.createStatement();
//添加一条或者多条 INSERT/UPDATE/DELETE 语句
statement.addBatch("INSERT INTO `test`(`id`,`name`) VALUES(1,'KevinBlandy');");
statement.addBatch("UPDATE `test` SET `name` = 'javaweb' WHERE `id` = 1;");
statement.addBatch("UPDATE `test` SET `name` = 'not_exists' WHERE `id` = 999;");
statement.addBatch("DELETE FROM `test` WHERE `id` = 1;");
//返回结果是int[],表示每条SQL执行后受影响的行数
int[] result = statement.executeBatch();
System.out.println("执行结果:" + Arrays.toString(result)); //执行结果:[1, 1, 0, 1]
connection.close();
PreparedStatement 批处理
PreparedStatement
可以使用占位符,没SQL注入的风险- 它一次性只能处理同一类型SQL语句
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "root", "root");
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `test`(`id`,`name`) VALUES(?,?);");
for(int x = 1 ;x <= 10 ;x++) {
preparedStatement.setInt(1, x);
preparedStatement.setString(2, "name_" + x);
//addBatch() 把SQL语句添加到批处理中。
preparedStatement.addBatch();
}
//执行批处理,返回受到影响的行数
int[] result = preparedStatement.executeBatch();
System.out.println("执行结果:" + Arrays.toString(result)); //执行结果:[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
//清空批处理
preparedStatement.clearBatch();
connection.close();