jdbc批量插入数据到MySQL

批量插入数据是指一次性插入多条记录到数据库中,这可以提高数据插入的效率。

前提条件

  1. 已经安装了MySQL数据库。
  2. 已经创建了数据库和表。
  3. 已经添加了MySQL JDBC驱动到项目的路径中。

如果没有添加jdbc可以参考:jdbc连接mysql(5种方式,循序渐进!!!)-CSDN博客

示例数据库和表

假设我们有一个名为t1的数据库,其中有一个名为users的表,结构如下:

sql 复制代码
CREATE TABLE t1 (
    id INT ,
    name VARCHAR(50)
);

Java代码示例

以下是一个Java程序,展示如何使用JDBC批量插入数据到t1表:

**注意:**一定要配置配置rewriteBatchedStatements参数

mysql.properties文件内容:

java 复制代码
user=root
password=root
url=jdbc:mysql://localhost:3306/mydb?rewriteBatchedStatements=true
driver=com.mysql.cj.jdbc.Driver

优化点

  • 使用addBatch()缓存SQL,executeBatch()批量提交。
  • 分批次处理(如每500条提交一次)。
java 复制代码
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
public class TestMysql {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            // 1. 加载配置文件
            Properties properties = new Properties();
            properties.load(new FileInputStream("src/mysql.properties"));
            String url = properties.getProperty("url");
            String user = properties.getProperty("user");  // 修正参数名更规范
            String password = properties.getProperty("password");
            String driver = properties.getProperty("driver");

            // 2. 注册驱动并获取连接
            Class.forName(driver);
            connection = DriverManager.getConnection(url, user, password);

            // 3. 关闭自动提交,开启事务
            connection.setAutoCommit(false);

            // 4. 准备SQL语句(建议常量用大写)
            String sql = "INSERT INTO t1 (id, name) VALUES (?, ?)";  // 明确字段名
            preparedStatement = connection.prepareStatement(sql);

            // 5. 批量插入50万条数据
            int batchSize = 500;
            long start = System.currentTimeMillis();
            for (int i = 0; i < 500000; i++) {
                preparedStatement.setInt(1, i + 1);  // 参数索引从1开始
                preparedStatement.setString(2, "张三");
                preparedStatement.addBatch();

                // 每500条提交一次(注意i从0开始,需+1判断)
                if ((i + 1) % batchSize == 0) {  // 修正条件判断
                    preparedStatement.executeBatch();
                    preparedStatement.clearBatch();
                }
            }

            // 6. 提交剩余未满batchSize的数据
            preparedStatement.executeBatch();

            // 7. 手动提交事务
            connection.commit();
            long end = System.currentTimeMillis();
            System.out.println("插入50万数据花费时间:"+(end-start));

        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            // 8. 异常回滚事务
            try {
                if (connection != null) {
                    connection.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

结果如下:(用了4秒左右)

在navicat查询数量:

相关推荐
ZWZhangYu1 小时前
LangChain 构建向量数据库和检索器
数据库·langchain·easyui
Python×CATIA工业智造1 小时前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
pianmian11 小时前
类(JavaBean类)和对象
java
我叫小白菜2 小时前
【Java_EE】单例模式、阻塞队列、线程池、定时器
java·开发语言
feifeigo1232 小时前
升级到MySQL 8.4,MySQL启动报错:io_setup() failed with EAGAIN
数据库·mysql·adb
狐凄2 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python
Albert Edison2 小时前
【最新版】IntelliJ IDEA 2025 创建 SpringBoot 项目
java·spring boot·intellij-idea
超级小忍3 小时前
JVM 中的垃圾回收算法及垃圾回收器详解
java·jvm
weixin_446122463 小时前
JAVA内存区域划分
java·开发语言·redis
悦悦子a啊3 小时前
Python之--基本知识
开发语言·前端·python