专修虚拟机 2015-12-04 08:09 采纳率: 0%
浏览 1768

PreparedStatement类的批处理问题

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的原因吗?求解!
  • 写回答

3条回答 默认 最新

  • Royal_lr 2015-12-04 08:21
    关注

    批处理不是什么数据库都行的,,不知道楼主用的是什么数据库

    评论

报告相同问题?