PreparedStatement批处理
什么是批处理?
当我们有多条sql语句需要发送到数据库执行的时候,有两种发送方式,一种是执行一条发送一条sql语句给数据库,另一个种是发送一个sql集合给数据库,也就是发送一个批sql到数据库。普通的执行过程是:每处理一条数据,就访问一次数据库;而批处理是:累积到一定数量,再一次性提交到数据库,减少了与数据库的交互次数,所以效率会大大提高,很显然两者的数据库执行效率是不同的,我们发送批处理sql的时候数据库执行效率要高
statement语句对象实现批处理有如下问题
缺点:采用硬编码效率低,安全性较差。
原理:硬编码,每次执行时相似SQL都会进行编译
PreparedStatement+批处理
优点:语句只编译一次,减少编译次数。提高了安全性(阻止了SQL注入)
原理:相似SQL只编译一次,减少编译次数
注意: 需要设置批处理开启&rewriteBatchedStatements=true
package com.msb.test4;import java.sql.*;/*** @Author: Ma HaiYang* @Description: MircoMessage:Mark_7001*/public class TestBatch {private static String driver ="com.mysql.cj.jdbc.Driver";private static String url="jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useServerPrepStmts=true&cachePrepStmts=true&&rewriteBatchedStatements=true";private static String user="root";private static String password="root";public static void main(String[] args) {testAddBatch();}// 定义一个方法,向部门表增加1000条数据public static void testAddBatch(){Connection connection = null;PreparedStatement preparedStatement=null;try{Class.forName(driver);connection = DriverManager.getConnection(url, user,password);String sql="insert into dept values (DEFAULT ,?,?)";preparedStatement = connection.prepareStatement(sql);//这里已经传入SQL语句//设置参数for (int i = 1; i <= 10663; i++) {preparedStatement.setString(1, "name");preparedStatement.setString(2, "loc");preparedStatement.addBatch();// 将修改放入一个批次中if(i%1000==0){preparedStatement.executeBatch();preparedStatement.clearBatch();// 清除批处理中的数据}}/** 整数数组中的元素代表执行的结果代号* SUCCESS_NO_INFO -2* EXECUTE_FAILED -3* *//*int[] ints = */preparedStatement.executeBatch();preparedStatement.clearBatch();}catch (Exception e){e.printStackTrace();}finally {if(null != preparedStatement){try {preparedStatement.close();} catch (SQLException e) {e.printStackTrace();}}if(null != connection){try {connection.close();} catch (SQLException e) {e.printStackTrace();}}}}}
JDBC中使用事务
事务概念:在逻辑上一组不可分割的操作,由多个sql语句组成,多个sql语句要么全都执行成功,要么都不执行. 原子性 一致性 隔离性 持久性
JDBC控制事物主要就是在学习如何让多个数据库操作成为一个整体,实现要么全都执行成功,要么全都不执行
在JDBC中,事务操作是自动提交。一条对数据库的DML(insert、update、delete)代表一项事务操作,操作成功后,系统将自动调用commit()提交,否则自动调用rollback()回滚,在JDBC中,事务操作方法都位于接口java.sql.Connection中,可以通过调用setAutoCommit(false)来禁止自动提交。之后就可以把多个数据库操作的表达式作为一个事务,在操作完成后调用commit()来进行整体提交,倘若其中一个表达式操作失败,都不会执行到commit(),并且将产生响应的异常;此时就可以在异常捕获时调用rollback()进行回滚,回复至数据初始状态.事务开始的边界则不是那么明显了,它会开始于组成当前事务的所有statement中的第一个被执行的时候。事务结束的边界是commit或者rollback方法的调用
preparedStatement.executeBatch(); 方法会直接修改数据数据库中的数据,无法起到事务的作用。
使用事务保证转账安全性package com.msb.test5;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;/*** @Author: Ma HaiYang* @Description: MircoMessage:Mark_7001*/public class TestTransaction {private static String driver ="com.mysql.cj.jdbc.Driver";private static String url="jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useServerPrepStmts=true&cachePrepStmts=true&&rewriteBatchedStatements=true";private static String user="root";private static String password="root";public static void main(String[] args) {testTransaction();}// 定义一个方法,向部门表增加1000条数据public static void testTransaction(){Connection connection = null;PreparedStatement preparedStatement=null;/** JDBC 默认是自动提交事务* 每条DML都是默认提交事务的,多个preparedStatement.executeUpdate();都会提交一次事务* 如果想手动控制事务,那么就不能让事务自动提交* 通过Connection对象控制connection.setAutoCommit(false);* 如果不设置 默认值为true,自动提交,设置为false之后就是手动提交了* 无论是否发生回滚,事务最终会一定要提交的 提交我们建议放在finally之中进行提交* 如果是转账的过程中出现异常了,那么我们就要执行回滚,回滚操作应该方法catch语句块中** */try{Class.forName(driver);connection = DriverManager.getConnection(url, user,password);// 设置事务手动提交connection.setAutoCommit(false);String sql="update account set money =money- ? where aid = ?";preparedStatement = connection.prepareStatement(sql);//这里已经传入SQL语句// 转出preparedStatement.setDouble(1, 100);preparedStatement.setInt(2, 1);preparedStatement.executeUpdate();// 产生异常//int i =1/0;// 转入preparedStatement.setDouble(1, -100);preparedStatement.setInt(2, 2);preparedStatement.executeUpdate();}catch (Exception e){if(null != connection){try {connection.rollback();// 回滚事务} catch (SQLException ex) {ex.printStackTrace();}}e.printStackTrace();}finally {// 提交事务if(null != connection){try {connection.commit();} catch (SQLException e) {e.printStackTrace();}}if(null != preparedStatement){try {preparedStatement.close();} catch (SQLException e) {e.printStackTrace();}}if(null != connection){try {connection.close();} catch (SQLException e) {e.printStackTrace();}}}}}
设置回滚点package com.msb.test5;import java.sql.*;import java.util.LinkedList;/*** @Author: Ma HaiYang* @Description: MircoMessage:Mark_7001*/public class TestTransaction2 {private static String driver ="com.mysql.cj.jdbc.Driver";private static String url="jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useServerPrepStmts=true&cachePrepStmts=true&&rewriteBatchedStatements=true";private static String user="root";private static String password="root";public static void main(String[] args) {testAddBatch();}// 定义一个方法,向部门表增加1000条数据public static void testAddBatch(){Connection connection = null;PreparedStatement preparedStatement=null;LinkedList<Savepoint> savepoints =new LinkedList<Savepoint>();try{Class.forName(driver);connection = DriverManager.getConnection(url, user,password);connection.setAutoCommit(false);String sql="insert into dept values (DEFAULT ,?,?)";preparedStatement = connection.prepareStatement(sql);//这里已经传入SQL语句//设置参数for (int i = 1; i <= 10663; i++) {preparedStatement.setString(1, "name");preparedStatement.setString(2, "loc");preparedStatement.addBatch();// 将修改放入一个批次中if(i%1000==0){preparedStatement.executeBatch();preparedStatement.clearBatch();// 清除批处理中的数据// 设置回滚点Savepoint savepoint = connection.setSavepoint();savepoints.addLast(savepoint);}// 数据在 100001条插入的时候出现异常if(i ==10001){int x =1/0;}}/** 整数数组中的元素代表执行的结果代号* SUCCESS_NO_INFO -2* EXECUTE_FAILED -3* *//*int[] ints = */preparedStatement.executeBatch();preparedStatement.clearBatch();}catch (Exception e){if(null != connection){try {//Savepoint sp = savepoints.getLast();Savepoint sp = savepoints.get(4);if(null != sp){// 选择回滚点connection.rollback(sp);// 回滚}} catch (SQLException e2) {e2.printStackTrace();}}e.printStackTrace();}finally {if(null != connection){try {connection.commit();// 提交} catch (SQLException e) {e.printStackTrace();}}if(null != preparedStatement){try {preparedStatement.close();} catch (SQLException e) {e.printStackTrace();}}if(null != connection){try {connection.close();} catch (SQLException e) {e.printStackTrace();}}}}}
