首页  

mysql JDBC rewriteBatchedStatements     所属分类 mysql 浏览量 292
默认情况下 无视executeBatch()语句,批量执行的一组sql语句,一条一条地发给MySQL数据库,
批量插入实际上是单条插入,性能低下

jdbc连接参数 加上 rewriteBatchedStatements=true

jdbc驱动5.1.13以上 ,才能实现高性能的批量插入

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            // 数据库连接
            String url = "jdbc:mysql://*************?autoReconnect=true&nullCatalogMeansCurrent=true&failOverReadOnly=false&useUnicode=true&characterEncoding=UTF-8";
            String user = "******";
            String password = "************";
            // 添加批处理参数
            //            url = url + "&rewriteBatchedStatements=true";
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, user, password);
            // 创建预编译 sql 对象
            statement = conn.prepareStatement("UPDATE table_test_demo set code = ? where id = ?");
            long a = System.currentTimeMillis(); 

            for (int i = 1; i <= 100; i++) {
                statement.setString(1, "测试1");
                statement.setInt(2, i);
                statement.addBatch(); 
            }

            long b = System.currentTimeMillis(); 
            System.out.println("添加参数耗时:" + (b-a)); 

            int[] r = statement.executeBatch(); 
            statement.clearBatch(); 

            long c = System.currentTimeMillis(); 
            System.out.println("执行sql耗时:" + (c-b)); 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            
            try {
                if (statement != null) {
                    statement.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

上一篇     下一篇
量化选基技术指标和公式

如何进行深度学习

提问的艺术

spring 组件类名相同 bean name冲突

获取有序数组中第一个大于等于目标值的索引

异常值检测的两种常用方法