Java通过JDBC向数据库批量插入数据(MySQL为例)

8 篇文章 0 订阅
6 篇文章 0 订阅

注:本文仅供学习参考,作者水平有限,如有错误还请指正!

         在数据库中需要大量插入或更新记录时,可以使用java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。

1、 JDBC的批量处理语句:
  • addBatch(String):添加需要批量处理的SQL语句或是参数;
  • executeBatch():执行批量处理语句;
  • clearBatch():清空缓存的数据
2、批量指向SQL语句的情况:
  • 多条SQL语句的批量处理
  • 一个SQL语句的批量处理
3、关于本案例的注意事项:
  • 该案例中使用的MySQL版本为8.0.x,故对应的mysql-connection-java驱动应为8.0.x

  • 5.x版本的驱动使用的驱动路径为:com.mysql.jdbc.Driver, 8.x版本的驱动路径为com.mysql.cj.jdbc.Driver

  • 在本案例的三、四中方式中使用了java的批处理(Batch),MySQL服务器默认是关闭的,我们需要通过一个参数,让mysql开启批处理支持。即,在配置文件的url后面加上参数“&rewriteBatchedStatements=true”。如下:

    user=root
    password=abc123
    url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useUnicode=true&rewriteBatchedStatements=true
    driverClass=com.mysql.cj.jdbc.Driver

  • 有关数据库的连接、插入等操作可参考博文:

    • 连接数据库:https://blog.csdn.net/m0_47015897/article/details/123206573?spm=1001.2014.3001.5501
    • 对数据库增删改查:https://blog.csdn.net/m0_47015897/article/details/123342211?spm=1001.2014.3001.5501
4、驱动程序
5、案例源码
  • 实验使用的表结构:
CREATE TABLE goods(
	id INT PRIMARY KEY AUTO_INCREMENT,
	NAME VARCHAR(25)
);
  • java源码
package com.Etui5.blob;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

import org.junit.Test;

import com.Etui3.util.JDBCUtils;

/**
 * 使用PreparedStatement实现批量数据的操作
 * 
 * update、delete本身就具备批量操作的效果
 * 此时的批量操作主要指的是批量插入。使用PreparedStatement实现更高效的批量操作
 * 
 * 方式一:使用Statement
 * 
 *
 */
public class insertTest {
	
	// 批量插入数据方式一:使用Statement
//	@Test 
	public void testInsert1() throws Exception {
		Connection conn = JDBCUtils.getConnection();
		Statement st = conn.createStatement();
		for(int i = 0; i < 20000; i++) {
			String sql = "insert into goods(name) values('nmae_" + i + "')";
			st.execute(sql);
		}
		conn.close();
		st.close();
	}
	
	// 方式二:使用PreparedStatement
//	@Test
	public void testInsert2() {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			long start = System.currentTimeMillis();
			conn = JDBCUtils.getConnection();
			String sql = "insert into goods(name) values(?)";
			ps = conn.prepareStatement(sql);
			for(int i = 0; i < 20000; i++) {
				ps.setObject(1, "name_" + i);
				ps.execute();
			}
			
			long end = System.currentTimeMillis();
			
			System.out.println("花费时间为:" + (end - start) + "ms"); // 20000条:51188ms
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.closeResource(conn, ps);			
		}
	}
	
	// 方式三:
	// 1、批量处理方式:addBatch(), executeBatch(), clearBatch()
	// 2、mysql 服务器默认是关闭批处理的,我们需要通过一个参数,让mysql开启批处理支持
	// 			?rewriteBatchedStatements=true写在配置文件的url后面
	// 3、使用更新的mysql驱动:5.1.37,该驱动需与mysql的版本对应,我使用的为8.0.27
	// 4、以往练习使用的都是5.1.7驱动,连接驱动为com.mysql.jdbc.Driver,8.0.x版本需改为com.mysql.cj.jdbc.Driver
//	@Test
	public void testInsert3() {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			long start = System.currentTimeMillis();
			conn = JDBCUtils.getConnection();
			String sql = "insert into goods(name) values(?)";
			ps = conn.prepareStatement(sql);
			for(int i = 0; i < 1000000; i++) {
				ps.setObject(1, "name_" + i);
//				ps.execute();
				
				// 每插入500条插入一次
				// 添加到批处理
				ps.addBatch();
				if(i % 500 == 0) {
					// 执行批量操作
					ps.executeBatch();
					// 清空batch
					ps.clearBatch();
				}
			}
			
			long end = System.currentTimeMillis();
			
			System.out.println("花费时间为:" + (end - start) + "ms"); // 20000条:349ms,1000000条:15833ms
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.closeResource(conn, ps);			
		}
	}
	
	// 方式四: 
	// 将自动提交关闭
	@Test
	public void testInsert4() {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			long start = System.currentTimeMillis();
			conn = JDBCUtils.getConnection();
			
			conn.setAutoCommit(false);// 关闭自动提交
			
			String sql = "insert into goods(name) values(?)";
			ps = conn.prepareStatement(sql);
			for(int i = 0; i < 1000000; i++) {
				ps.setObject(1, "name_" + i);
				ps.addBatch();
				if(i % 500 == 0) {
					ps.executeBatch();
					ps.clearBatch();
				}
			}
			
			conn.commit();// 预处理完成后统一提交
			
			long end = System.currentTimeMillis();
			
			System.out.println("花费时间为:" + (end - start) + "ms"); // 1000000条:9505ms
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.closeResource(conn, ps);			
		}
	}
}

  • 5
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
JavaMySQL批量存储数据可以使用批处理(batch)的方式进行,这样可以大大提高插入数据的效率。下面是一个简单的示例代码: ```java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class BatchInsertDemo { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "123456"; try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false);//关闭自动提交事务 PreparedStatement pstmt = conn.prepareStatement("insert into user(name, age) values (?, ?)"); for (int i = 1; i <= 10000; i++) { pstmt.setString(1, "user" + i); pstmt.setInt(2, i % 100); pstmt.addBatch();//添加到批处理中 } pstmt.executeBatch();//批量执行 conn.commit();//提交事务 pstmt.close(); conn.close(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们创建了一个名为`BatchInsertDemo`的类,其中定义了一个`main()`方法。在`main()`方法中,我们首先定义了连接MySQL的URL、用户名和密码,然后使用`Class.forName()`方法加载了MySQL的驱动程序。接下来,我们通过`DriverManager.getConnection()`方法获得了与MySQL数据库的连接,并将自动提交事务关闭。 然后,我们使用`PreparedStatement`对象执行了一条插入语句,并使用`addBatch()`方法将其添加到批处理中。在循环结束后,我们使用`executeBatch()`方法批量执行所有的插入语句,并将事务提交。最后,我们关闭了`PreparedStatement`对象和数据库连接。 需要注意的是,批量插入数据时,每次插入的数据量不宜过大,否则可能会导致内存溢出或性能下降。一般来说,每批次插入的数据量在几千到一万条之间比较合适。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值