JDBC—批处理的基本用法

大城市里の小女人 提交于 2020-03-01 05:54:28

批处理的基本用法

批处理时:先把事务设置为手动提交,然后尽量使用 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();
			}
		}
	}
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!