How to avoid multiple insert in PostgreSQL

后端 未结 2 1469
醉梦人生
醉梦人生 2021-01-26 16:36

In my query im using for loop. Each and every time when for loop is executed, at the end some values has to be inserted into table. This is time consuming because for loop has m

相关标签:
2条回答
  • 2021-01-26 17:10

    If you show how the variables are calculated it could be possible to build something like this:

    insert into datas.tb
    select
        calculate_j_here,
        calculate_predicted_node_here
    from generate_series(1, 10000)
    
    0 讨论(0)
  • 2021-01-26 17:16

    One possible solution is to build a large VALUES String. In Java, something like

    StringBuffer buf = new StringBuffer(100000); // big enough?
    for ( int i=1; i<=10000; ++i ) {
        buf.append("(")
           .append(j)
           .append(",")
           .append(predicted_node)
           .append("),"); // whatever j and predict_node are
    }
    buf.setCharAt(buf.length()-1, ' '); // kill last comma
    String query = "INSERT INTO datas.tb VALUES " + buf.toString() + ";"
    // send query to DB, just once
    

    The fact j and predict_node appear to be constant has me a little worried, though. Why are you putting a constant in 100000 times?

    Another approach is to do the predicting in a Postgres procedural language, and have the DB itself calculate the value on insert.

    0 讨论(0)
提交回复
热议问题