JDBC—批处理的基本用法

批处理的基本用法

批处理时:先把事务设置为手动提交,然后尽量使用 Statement

/*
 *  测试批处理的基本用法
 *  对于大量的批处理,建议使用Statement,因为PreparedStatement的预编译空间有限当数据量特别大时,会发生异常。
 *  批处理时先把事务设置为手动提交,然后尽量使用 Statement
 */
public class Demo05 {
	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			// 加载驱动类
			Class.forName("com.mysql.jdbc.Driver");
			// 建立连接(连接对象内部其实包含了Socket对象,是一个远程的连接。比较耗时!这是Connection对象管理的一个要点!)
			// 真正开发中,为了提高效率,都会使用连接池来管理连接对象!
			conn = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/testjdbc?useUnicode=true&characterEncoding=UTF-8", "root", "root");
			// JDBC中默认是true,自动提交事务
			conn.setAutoCommit(false); // 事务设置为手动提交
			long start = System.currentTimeMillis();
			stmt = conn.createStatement();

			for (int i = 0; i < 20000; i++) {
				stmt.addBatch("insert into t_user (username,pwd,regTime) values ('lin" + i + "',666666,now())");
			}
			
			stmt.executeBatch(); // 执行批处理
			conn.commit(); // 提交事务
			long end = System.currentTimeMillis();
			System.out.println("插入20000条数据,耗时(毫秒):" + (end - start));
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			// 后开的先关
			// 关闭顺序遵循:ResultSet --> Statement --> Connection这样的关闭顺序!一定要将三个trycatch块分开写!
			try {
				if (rs != null) {
					rs.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if (stmt != null) {
					stmt.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			// 关闭 Connection
			try {
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值