java 批处理

来源:互联网 发布:电信4g网络覆盖 编辑:程序博客网 时间:2024/06/06 05:58
 
  1. import java.sql.BatchUpdateException;   
  2. import java.sql.Connection;   
  3. import java.sql.DriverManager;   
  4. import java.sql.PreparedStatement;   
  5. import java.sql.Statement;   
  6.   
  7. public class DemoPreparedStatementAddBatchMySQL {   
  8.   
  9.   public static Connection getConnection()throws Exception {   
  10.      String driver = "org.gjt.mm.mysql.Driver";   
  11.      String url = "jdbc:mysql://localhost/databaseName";   
  12.      String username = "root";   
  13.      String password = "root";   
  14.      Class.forName(driver);   
  15.      Connection conn = DriverManager.getConnection(url, username, password);   
  16.     return conn;   
  17.    }   
  18.   
  19.   public staticvoid checkUpdateCounts(int[] updateCounts) {   
  20.     for (int i =0; i < updateCounts.length; i++) {   
  21.       if (updateCounts[i] >= 0) {   
  22.          System.out.println("Successfully executed; updateCount=" + updateCounts[i]);   
  23.        } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {   
  24.          System.out.println("Successfully executed; updateCount=Statement.SUCCESS_NO_INFO");   
  25.        } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {   
  26.          System.out.println("Failed to execute; updateCount=Statement.EXECUTE_FAILED");   
  27.        }   
  28.      }   
  29.    }   
  30.   
  31.   public staticvoid main(String[] args)throws Exception {   
  32.      Connection conn = null;   
  33.      PreparedStatement pstmt = null;   
  34.     try {   
  35.        conn = getConnection();   
  36.        conn.setAutoCommit(false);   
  37.        String query = "insert into add_batch_table(stringCol, intCol) values(?, ?)";   
  38.        pstmt = conn.prepareStatement(query);   
  39.        pstmt.setString(1, "1");   
  40.        pstmt.setInt(2,100);   
  41.        pstmt.addBatch();   
  42.   
  43.        pstmt.setString(1, "2");   
  44.        pstmt.setInt(2,200);   
  45.        pstmt.addBatch();   
  46.   
  47.        pstmt.setString(1, "3");   
  48.        pstmt.setInt(2,300);   
  49.        pstmt.addBatch();   
  50.   
  51.       int[] updateCounts = pstmt.executeBatch();   
  52.        checkUpdateCounts(updateCounts);   
  53.        conn.commit();   
  54.      } catch (BatchUpdateException e) {   
  55.       int[] updateCounts = e.getUpdateCounts();   
  56.        checkUpdateCounts(updateCounts);   
  57.       try {   
  58.          conn.rollback();   
  59.        } catch (Exception e2) {   
  60.          e.printStackTrace();   
  61.        }   
  62.      } catch (Exception e) {   
  63.        e.printStackTrace();   
  64.      } finally {   
  65.        pstmt.close();   
  66.        conn.close();   
  67.      }   
  68.    }   
  69. }