public class Batch {
public void batchAdd(){
Connection con=null;
PreparedStatement stmt=null;
String sql=null;
try{
sql = "insert into emp(empno, ename, sal) values(?,?,?)";
con=ConnectionSource.getConnection();
stmt=con.prepareStatement(sql);
//关闭自动提交
con.setAutoCommit(false);
for(int i=1000;i<105;i++){
stmt.setInt(1, i);
stmt.setString(2, "name"+i);
stmt.setDouble(3, new Random().nextInt(10000));
// 加入到Batch中
stmt.addBatch();
}
//执行批处理
stmt.executeBatch();
//提交
con.commit();
}catch(SQLException e){
System.out.println("数据库访问异常");
throw new RuntimeException(e);
}finally{
try{
if(stmt!=null){
stmt.close();
}
if(con!=null){
con.close();
}
}catch(SQLException e){
System.out.println("释放资源时发生异常");
}
}
}
写了个
PreparedStatement类的批处理 运行后不会报错 但是数据库中也没有数据!不知道什么原因?难道是因为PreparedStatement的占位符放在for的原因吗?求解!