使用PreparedStatement实现批量数据的操作

使用PreparedStatement实现批量数据的操作

package com.sammery.Blob;

import java.sql.Connection;
import java.sql.PreparedStatement;
import org.junit.Test;

import com.sammery.util.JDBCUtils;

/*
 * 使用PreparedStatement实现批量数据的操作
 * 
 * update、delete本身具有批量操作的效果。
 * 此时的批量操作,主要指的是批量插入。使用PreparedStatement如何实现更高效的批量插入?
 * 
 * 题目:想goods表中插入20000条数据
 *  CREATE TABLE goods (
	id INT PRIMARY KEY AUTO_INCREMENT,
	`name` VARCHAR(25)
	);
 * 方式一:使用Statement
 * 	Connection connection = JDBCUtils.getConnection();
	Statement statement = connection.createStatement();
	for (int i = 0; i <= 20000; i++) {
		String sql = "INSERT INTO goods(`name`) VALUES(`name_"+i+"`)";
		statement.execute(sql);
	}
 * */

public class InsertTest {
	//方式二:使用PreparedStatement批量插入数据
	//20000条运行时间:60374毫秒
	@Test
	public void testInsert2() throws Exception{
		Connection connection = null;
		PreparedStatement ps = null;
		try {
			long start = System.currentTimeMillis();
			
			connection = JDBCUtils.getConnection();
			String sql = "INSERT INTO goods(`name`) VALUES(?)";
			ps = connection.prepareStatement(sql);
			for (int i = 1; i <= 20000; i++) {
				ps.setObject(1, "name_"+i);
				ps.execute();
			}
			long end = System.currentTimeMillis();
			
			System.out.println("运行时间:"+(end-start)+"毫秒");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.closeResource(connection, ps);
		}
	}
	
	
	/*
	 * 批量操作方式三:
	 * 1.addBatch()、executeBatch()、clearBatch()
	 * 2.mysql服务器默认是关闭批处理的,我们需要通过一个参数,让MySQL开启批处理的支持。
	 * 		?rewriteBatchedStatements=true 写在配置文件的url后面
	 * 3.使用更新的MySQL驱动:mysql-connector-java-5.1.37-bin.jar
	 * 
	 * 20000运行时间:731毫秒
	 * 1000000运行时间:13088毫秒
	 * */
	@Test
	public void testInsert3() throws Exception{
		Connection connection = null;
		PreparedStatement ps = null;
		try {
			long start = System.currentTimeMillis();
			
			connection = JDBCUtils.getConnection();
			String sql = "INSERT INTO goods(`name`) VALUES(?)";
			ps = connection.prepareStatement(sql);
			for (int i = 1; i <= 1000000; i++) {
				ps.setObject(1, "name_"+i);
				
				//1."攒"sql
				ps.addBatch();
				if(i % 500 == 0){
					//2.攒够500条执行
					ps.executeBatch();
					
					//3.清空Batch
					ps.clearBatch();
				}
			}
			long end = System.currentTimeMillis();
			
			System.out.println("运行时间:"+(end-start)+"毫秒");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.closeResource(connection, ps);
		}
	}
	
	/*
	 * 批量操作方式四:设置连接不允许自动提交数据
	 * 1000000运行时间:6241毫秒
	 * */
	@Test
	public void testInsert4() throws Exception{
		Connection connection = null;
		PreparedStatement ps = null;
		try {
			long start = System.currentTimeMillis();
			
			connection = JDBCUtils.getConnection();
			
			//设置不允许自动提交数据
			connection.setAutoCommit(false);
			
			String sql = "INSERT INTO goods(`name`) VALUES(?)";
			ps = connection.prepareStatement(sql);
			for (int i = 1; i <= 1000000; i++) {
				ps.setObject(1, "name_"+i);
				
				//1."攒"sql
				ps.addBatch();
				if(i % 500 == 0){
					//2.攒够500条执行
					ps.executeBatch();
					
					//3.清空Batch
					ps.clearBatch();
				}
			}
			
			//提交数据
			connection.commit();
			
			long end = System.currentTimeMillis();
			
			System.out.println("运行时间:"+(end-start)+"毫秒");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.closeResource(connection, ps);
		}
	}

}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java 中可以使用 JDBCJava Database Connectivity)来实现数据批量插入。具体操作步骤如下: 1. 建立数据库连接; 2. 创建 PreparedStatement 对象,使用 SQL 语句创建; 3. 使用 PreparedStatement 的 addBatch() 方法添加多条 SQL 语句; 4. 使用 PreparedStatementexecuteBatch() 方法执行批量操作; 5. 提交事务; 6. 关闭 PreparedStatement数据库连接。 下面是一个示例代码,假设要将多个用户信息批量插入到数据库中: ```java Connection conn = null; PreparedStatement pstmt = null; try { // 建立数据库连接 conn = DriverManager.getConnection(url, user, password); // 创建 PreparedStatement 对象 String sql = "INSERT INTO user (id, name, age) VALUES (?, ?, ?)"; pstmt = conn.prepareStatement(sql); // 添加多条 SQL 语句 for (User user : users) { pstmt.setInt(1, user.getId()); pstmt.setString(2, user.getName()); pstmt.setInt(3, user.getAge()); pstmt.addBatch(); } // 执行批量操作 int[] results = pstmt.executeBatch(); // 提交事务 conn.commit(); } catch (SQLException e) { // 回滚事务 conn.rollback(); e.printStackTrace(); } finally { // 关闭 PreparedStatement数据库连接 if (pstmt != null) { pstmt.close(); } if (conn != null) { conn.close(); } } ``` 其中,users 是一个 User 对象的集合,表示多个用户信息。在添加 SQL 语句时,使用 PreparedStatement 的 setXXX() 方法设置占位符的值,然后使用 addBatch() 方法添加到批量操作中。执行 executeBatch() 方法后,会返回一个 int 数组,表示每个 SQL 语句执行的结果。最后,需要提交事务并关闭 PreparedStatement数据库连接。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值