JDBC_批处理Batch_插入2万条数据的测试

批处理   Batch

对于大量的批处理,建议使用Statement,因为PreparedStatement的预编译空间有限,当数据特别大时,会发生异常。

import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
* 测试批处理的基本用法
*
* @author Administrator
*/
public class Demo005 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost/testjdbc", "root", "");
conn.setAutoCommit(false);// 设为手动提交
stmt = conn.createStatement();
for (int i = 0; i < 1000; i++) {
stmt.addBatch("insert into t_user(username,pwd,regTime)values('qi"
+ i + "',8888,now())");
}
stmt.executeBatch();
conn.commit();// 提交事务
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}

猜你喜欢

转载自www.cnblogs.com/qhcyp/p/10452994.html