1. 程式人生 > >JDBC獲取自增主鍵,批量操作

JDBC獲取自增主鍵,批量操作

一:jdbc獲取資料庫自增主鍵
使用場景:插入一個記錄之後需要直接使用該記錄進行別的操作,例如插入一個訂單之後需要對訂單詳情表中插入訂單項紀錄,需要使用該個主鍵作為訂單項表的外來鍵(前提是訂單表主鍵是自增型別)

    //例
@Test
public void test(){
    Connection connection=null;
    PreparedStatement preparedStatement=null;
    ResultSet resultSet=null;
    String sql="insert into order(otime,total) values (?,?);"
; try { //獲取連線 connection=DBUtils.getConnection(); //獲取可以得到自增主鍵的preparedstatement preparedStatement=connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); preparedStatement.setDate(1, new Date(new java.util.Date().getTime())); preparedStatement.
setDouble(2, 200.5); preparedStatement.executeUpdate(); //獲取自增主鍵 resultSet=preparedStatement.getGeneratedKeys(); if(resultSet.next()){ System.out.println(resultSet.getObject(1)); } } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.
close(connection, preparedStatement, resultSet); } }

二:批量操作
如果一次操作大批量的資料,使用迴圈逐條操作代價太大,批量操作可以大幅度提高效能

@Test
public void test(){
    //例插入十萬條資料
    Connection connection=null;
    PreparedStatement preparedStatement=null;
    String sql="insert into person values (?,?,?);";
    try {
        //涉及事物操作
        connection=DBUtils.getConnection();
        DBUtils.startTransacton(connection);

        long start=System.currentTimeMillis();
        for(int i=1;i<=100000;i++){
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setInt(1, i);
            preparedStatement.setString(2, "name"+i);
            preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
            //批處理
            preparedStatement.addBatch();
            //每執行五百條資料操作執行一次批處理,並且將批處理清空
            if((i%500==0)){
                preparedStatement.executeBatch();
                preparedStatement.clearBatch();
            }
        }
        //將最後剩餘的資料操作進行處理
        preparedStatement.executeBatch();
        preparedStatement.clearBatch();
        long end=System.currentTimeMillis();
        DBUtils.commit(connection);
        System.out.println("批量方法新增十萬條資料用時:"+(end-start)+"毫秒");
    } catch (Exception e) {
        e.printStackTrace();
        DBUtils.rollback(connection);
    } finally {
        DBUtils.close(connection, preparedStatement, null);
    }
}

三:Apache dbutils中的獲取資料庫自增主鍵

    @Test
    public void test(){
        QueryRunner qr=new QueryRunner(DBUtils.getDataSource());
        String sql="insert into department values(null,'java')";
        try {
            Long keys=qr.insert(sql, new ScalarHandler<Long>());
            System.out.println(keys);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

四:Apache dbutils 批量操作

    @Test
    public void testBatch(){
        String sql="delete from department where id=?";
        QueryRunner qr=new QueryRunner(DBUtils.getDataSource());
        int[] is={4,7,8};
        //定義引數陣列
        //行數表示需要操作的記錄條數,有幾行操作幾行資料
        Object[][] params=new Object[is.length][];
        //每一行的資料也就是需要填充的引數
        for (int i = 0; i < params.length; i++) {
            params[i]=new Object[]{is[i]};
        }
        try {
            //返回的結果是每一組資料的操作結果0/1,陣列長度也就是操作記錄的條數(行數)
            int[] batch = qr.batch(sql, params);
            for (int i : batch) {
                System.out.println(i);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }