PreparedStatement.setXxx(1,xxx);//准备好sql语句*大量
PreparedStatement.addBatch();//将SQL语句添加到批处理
PreparedStatement.executeBatch();//处理大量sql语句
PreparedStatement.clearBatch();//将批量处理过的sql语句清空,等再次添加一组
使用批处理的前提是需要在连接数据库的url中配置rewriteBatchedStatements=true
批处理的底层是创建了一个ArrayList数组,初次创建长度为10,满后按照1.5倍扩容
user=root
password=cxl
url=jdbc:mysql://localhost:3306/testdb?rewriteBatchedStatements=true
#如果使用批量处理,则必须在url中添加 ?rewriteBatchedStatements=true
driver=com.mysql.jdbc.Driver
CRUD:
PreparedStatement preparedStatement = connection.preparedStatement(sql);
preparedStatement.setXxx(int n,xxx);//n代表第几个?,Xxx代表xxx的数值类型
int n = preparedStatement.executeUpdate();//增删改,n为执行结果影响的行数,当n>0,说明执行成功
ResultSet resultSet = preparedStatement.executeQuery();//查,resultSet为查询结果
while(resultSet.next()){
Xxx xx = resultSet.getXxx("字段名");
//String s = resultSet.getString("name");或者 getString(3),3代表name为表的第几列
System.out.print(xxx);
}
//最后关闭资源
事务:
Connection.setAutoCommit(false);//开启事务
Connection.rollback();//回滚,可以无参,也可以传入保存点
Connection.setSavepoint();设置保存点,可以无参,也可以传入String类型的保存点名
Connection.commit();//提交事务