@Override
public void addAllEmp(List<Employee> employees) {
Connection conn = null;
PreparedStatement pst = null;
try {
conn = JDBCUtil.getConnect();
conn.setAutoCommit(false);
pst = conn.prepareStatement("insert into jdbc_emp values(jdbc_emp_id.nextval,?,?,?");
int count = 0;
for (Employee employee : employees) {
pst.setString(1, employee.getName());
pst.setString(2, employee.getPassword());
pst.setDouble(3, employee.getSal());
count++;
if (count==100) {
//执行批处理
pst.executeBatch();
//清空参数
pst.clearParameters();
count = 0;
}
}
pst.executeBatch();
conn.commit();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
/*if (conn != null) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}*/
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JDBCUtil.close(conn, pst);
}

JAVA中使用JDBC做批量处理时,没有报错,但是数据没有插入数据库
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- engchina 2017-04-17 00:42关注
试下下面代码。
1,insert语句后面漏了个 )
2,追加 pst.addBatch();@Override public void addAllEmp(List<Employee> employees) { Connection conn = null; PreparedStatement pst = null; try { conn = JDBCUtil.getConnect(); conn.setAutoCommit(false); // add ")" for missing // pst = conn.prepareStatement( // "insert into jdbc_emp values(jdbc_emp_id.nextval,?,?,?"); pst = conn.prepareStatement( "insert into jdbc_emp values(jdbc_emp_id.nextval,?,?,?)"); int count = 0; for (Employee employee : employees) { pst.setString(1, employee.getName()); pst.setString(2, employee.getPassword()); pst.setDouble(3, employee.getSal()); // add addBatch() pst.addBatch(); count++; if (count == 100) { // 执行批处理 pst.executeBatch(); // 清空参数 pst.clearParameters(); count = 0; } } pst.executeBatch(); conn.commit(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { /* * if (conn != null) { try { conn.rollback(); } catch (SQLException * e1) { e1.printStackTrace(); } } */ // TODO Auto-generated catch block e.printStackTrace(); } finally { JDBCUtil.close(conn, pst); } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报