批处理的基本用法
批处理时:先把事务设置为手动提交,然后尽量使用 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();
}
}
}
}
来源:CSDN
作者:林伟茂-Summer
链接:https://blog.csdn.net/weixin_42814000/article/details/104575541