PreparedStatement批量处理和事务
- PreparedStatement批量处理和事务代码如下:
-
-
- public class PreparedStatementCommitAndRollback {
- public static void main(String args[]) {
- Connection con = null;
- PreparedStatement pstm = null;
-
- try {
-
- con = JDBCUtil.getConnection();
-
-
- pstm = con.prepareStatement("insert into student values(?,?,?,?)");
- con.setAutoCommit(false);
-
- pstm.setInt(1, 33);
- pstm.setString(2,"wangqin");
- pstm.setString(3, "c++");
- pstm.setDouble(4, 78.5);
-
- pstm.addBatch();
-
- pstm.setInt(1, 34);
- pstm.setString(2,"wuytun");
- pstm.setString(3, "c");
- pstm.setDouble(4, 77);
-
- pstm.addBatch();
-
- pstm.setInt(1, 31);
- pstm.setString(2,"tetet");
- pstm.setString(3, "c++");
- pstm.setDouble(4, 90);
-
- pstm.addBatch();
-
- pstm.setInt(1, 32);
- pstm.setString(2,"liug");
- pstm.setString(3, "c");
- pstm.setDouble(4, 50);
-
- pstm.addBatch();
-
- pstm.executeBatch();
- System.out.println("插入成功!");
-
- con.commit();
- System.out.println("提交成功!");
- con.setAutoCommit(true);
-
- } catch (SQLException e) {
- try {
-
- if(!con.isClosed()){
- con.rollback();
- System.out.println("插入失败,回滚!");
- con.setAutoCommit(true);
- }
- } catch (SQLException e1) {
- e1.printStackTrace();
- }
- }finally{
- JDBCUtil.closePreparedStatement(pstm);
- JDBCUtil.closeConnection(con);
- }
- }
- }
- 这是Statement的代码,同上:
- stm = con.createStatement();
- con.setAutoCommit(false);
-
- 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.addBatch("insert into student values(26,'溜出','英语',89)");
- stm.addBatch("insert into student values(27,'wqde','java',63)");
-
- stm.executeBatch();
原文地址:https://www.cnblogs.com/zmc/p/7010893.html