在t1中更新一行,而在t2中插入许多行

时间:2019-05-09 19:40:57

标签: java postgresql

我不知道应该使用2个单独的查询还是只能使用1个。

我需要UPDATErecords中的一行,然后INSERT 50,000行到表runners中。

records

rc_id   runner       msg  
    1     bill    'hello'

runners

r_id    runner   km_run  
   1      mary      3.5
   2      anna      1.5
   3      john      6.5
   4      bill      1.5
   5      jess      6.2
   6      jack      2.5

我可以像下面这样编写查询,但是它将与我的代码中的UPDATE一起在每一批中执行INSERT

给出我的Java代码,如何调整此查询,以便一次执行UPDATE,一次执行INSERT 50,000次。如果2个查询是标准方法,请让我知道。

Working SQLFiddle

WITH r_updater AS
  (UPDATE records
   SET msg = 'goodbye'
   WHERE runner = 'bill' )
INSERT INTO runners (runner, km_run)
VALUES ('george', 2.3) ON CONFLICT (runner, km_run) DO
UPDATE
SET runner=EXCLUDED.runner,
    km_run=EXCLUDED.km_run;

Java代码:

   Connection conn = null;
   PreparedStatement stmt = null;
   try {
       conn = MyDBSource.getInstance().getConnection();

    // This is the first of 2 queries I'm running. I want to combine them somehow
       String updateQuery = "UPDATE records
       SET msg = 'goodbye'
       WHERE runner = 'bill';
       stmt = conn.prepareStatement(updateQuery);
       stmt.executeUpdate();

       conn.setAutoCommit(false);

       String insertQuery = "INSERT INTO runners (runner, km_run)
       VALUES(?, ?)
       ON CONFLICT(runner, km_run)
       DO UPDATE
       SET
       runner = EXCLUDED.runner,
       km_run = EXCLUDED.km_run;"

       stmt = conn.prepareStatement(insertQuery);
       int batchSize = 100;
       int rows = 0;

       for (RunnerModel runnerModel: runnerModelMap.entrySet()) {
           int i = 0;
           stmt.setString(++i, runnerModel.getRunner());
           stmt.setString(++i, runnerModel.getKmRun());
           stmt.addBatch();
           if (++rows % batchSize == 0) {
               stmt.executeBatch();
           }
       }
       if (rows % batchSize != 0) {
           stmt.executeBatch();
       }
       conn.commit();
   } catch (SQLException e) {
       e.getNextException().printStackTrace();
   } finally {
       closeResources(stmt, conn);

   }

如果您想知道为什么我完全使用HashMapsee here.

0 个答案:

没有答案