jdbc SQL的批处理:
也就是一次增加多条数据,修改多条数据之类,可在传入参数时做一个for循环,然后再executeUpdate()
也可以通过addBatch()进行批处理
package com.msb.test1;
import java.sql.*;
public class TestJDBCBach {
private static String driver = "com.mysql.cj.jdbc.Driver";
private static String url = "jdbc:mysql://127.0.0.1:3306/green?UseSSL=false&&useUnicode=true&&charecterEncoding=UTF-8&ServerTimezone=Asia/shanghai&userServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true";
private static String user = "root";
private static String password = "root";
public static void main(String[] args){
testQuery();
}
//查询
public static void testQuery(){
Statement statement = null;
Connection connection = null;
ResultSet resultSet = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
String sql = "insert into activity values(DEFAULT,?,?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql); //获取语句对象
int rows = 0;
for (int i = 0; i < 100; i++) {
preparedStatement.setString(1,"单");
preparedStatement.setString(2,"广州");
preparedStatement.setString(3,"生活");
preparedStatement.setString(4,"增城");
/**
* &userServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true
* userServerPrepStmts:是否开启预编译
* cachePrepStmts:是否启动预编译缓存
* rewriteBatchedStatements:批处理
*/
preparedStatement.addBatch(); //将sql语句放入一个批次中,再一起执行
}
int[] ints = preparedStatement.executeBatch(); //成功返回-2,失败返回-3
for (int anInt : ints) {
rows += anInt;
}
System.out.println(rows);
preparedStatement.clearBatch(); //清除批处理中的数据
}catch (Exception e){
e.printStackTrace();
}finally {
if(null != statement) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (null != connection){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}