Skip to content

通过Statement进行批量数据操作

注意:

  • 执行批处理操作前,自动提交模式设置为FALSE
  • 执行批处理操作,并进行手动提交(commit)
  • 执行批处理操作后,自动提交模式恢复为 TRUE
  • 执行批处理操作异常发生时,进行 rollback(回滚)

示例: 通过 Statement 批量操作数据

try {
  //创建Statement对象
  stm = con.createStatement();
  //设置事务非自动提交
  con.setAutoCommit(false);   
  // 添加多条SQL语句到批处理中
  stm.addBatch("insert into student values(23,'tangbao','高数',100)");
  stm.addBatch("insert into student values(24,'王定','c#',98)");
  stm.addBatch("insert into student values(25,'王国云','java',90)");
  //执行批处理操作  
  stm.executeBatch();   
  System.out.println("插入成功!");   
  //执行成功后进行数据提交
  con.commit();   
  System.out.println("提交成功!");
  //关闭非自动提交
  con.setAutoCommit(true);   
} catch (SQLException e) {   
  if (!con.isClosed()) {
    con.rollback(); //出现异常,回滚事务
    System.out.println("提交失败,回滚!");
    con.setAutoCommit(true); //关闭非自动提交
  }
} finally {
  if (stmt != null) {
    //关闭操作对象
    stmt.close();
  }
}