@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);
}
試下下面代碼。
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);
}
}