
文章插图

文章插图
- 使用了事务(useTransaction)之后:可以看到由于在catch语句中进行了回滚操作 , 在捕获到异常之后直接进行回滚 , 保证数据的一致性

文章插图

文章插图
9.批处理
- 基本介绍
- 当需要成批插入或者更新记录时 , 可以采用Java的批量更新机制 , 这一机制允许多条语句一次性提交给数据库批量处理 。通常情况下比单独提交处理更有效率
- JDBC的批量处理语句包括下面方法:
- addBatch():添加需要批量处理的SQL语句或参数
- executeBatch():执行批量处理语句
- clearBatch():清空批处理包的语句
- JDBC连接MySQL时 , 如果要使用批处理功能 , 请在url中加参数?rewriteBatchedStatements=true
- 批处理往往和PreparedStatement一起搭配使用 , 可以既减少编译次数 , 又减少运行次数 , 效率大大提高
例子
- 演示向admin2表中添加5000条数据 , 看看使用批处理耗时多久
- 注意批处理需要修改配置文件的数据:url=jdbc:mysql://localhost:3306/数据库?rewriteBatchedStatements=true
user=rootpassword=123456url=jdbc:mysql://localhost:3306/hsp_db02?rewriteBatchedStatements=truedriver=com.mysql.jdbc.Driver首先创建测试表admin2CREATE TABLE admin2( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(32) NOT NULL, PASSWORD VARCHAR(32) NOT NULL );SELECT COUNT(*) FROM admin2;测试程序:package li.jdbc.batch_;import li.jdbc.utils.JDBCUtils;import org.junit.Test;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;/** * 演示java的批处理 */public class Batch_ {//传统方法 , 添加5000条数据到admin2@Testpublic void noBatch() throws Exception {//获取连接Connection connection = JDBCUtils.getConnection();//sqlString sql = "insert into admin2 values (null,?,?)";PreparedStatement preparedStatement = connection.prepareStatement(sql);System.out.println("开始执行");long start = System.currentTimeMillis();for (int i = 0; i < 5000; i++) {preparedStatement.setString(1, "jack" + i);preparedStatement.setString(2, "666");preparedStatement.executeUpdate();}long end = System.currentTimeMillis();System.out.println("传统的方式耗时:" + (end - start));//关闭连接JDBCUtils.close(null, preparedStatement, connection);}//使用批量方式添加数据--注意在配置文件添加参数?rewriteBatchedStatements=true@Testpublic void batch() throws Exception {//获取连接Connection connection = JDBCUtils.getConnection();//sqlString sql = "insert into admin2 values (null,?,?)";PreparedStatement preparedStatement = connection.prepareStatement(sql);System.out.println("开始执行");long start = System.currentTimeMillis();for (int i = 0; i < 5000; i++) {preparedStatement.setString(1, "jack" + i);preparedStatement.setString(2, "666");//将SQL语句加入到批处理包中preparedStatement.addBatch();//当有1000条SQL时 , 再批量执行if ((i + 1) % 1000 == 0) {//每满1000条时 , 就批量执行preparedStatement.executeBatch();//执行完就清空批处理包preparedStatement.clearBatch();}}long end = System.currentTimeMillis();System.out.println("批量方式耗时:" + (end - start));//关闭连接JDBCUtils.close(null, preparedStatement, connection);}}
文章插图
经验总结扩展阅读
- 哪些星座情侣就算是吵架也能快速和好
- 爱情和友情分得一清二楚的星座
- 要怎么和十二星座谈恋爱才能走得久
- 哪些星座喜欢和幼稚的人谈恋爱
- 和男朋友总是有疏离感的星座女
- 和哪些星座谈恋爱要超级有仪式感
- 红米note11和红米note10有什么区别_哪款更值得入手
- 小米11有什么缺点_小米11缺点和不足
- 红米note11pro和红米note10pro有什么区别_参数配置对比
- 2022年二月以后天气是不是越来越暖和 今年二月份天气是多少度
