Efficient way to do batch INSERTS with JDBC

前端 未结 10 774
无人共我
无人共我 2020-11-22 14:12

In my app I need to do a lot of INSERTS. Its a Java app and I am using plain JDBC to execute the queries. The DB being Oracle. I have enabled batching though, so it saves me

10条回答
  •  生来不讨喜
    2020-11-22 14:53

    In my code I have no direct access to the 'preparedStatement' so I cannot use batch, I just pass it the query and a list of parameters. The trick however is to create a variable length insert statement, and a LinkedList of parameters. The effect is the same as the top example, with variable parameter input length.See below (error checking omitted). Assuming 'myTable' has 3 updatable fields: f1, f2 and f3

    String []args={"A","B","C", "X","Y","Z" }; // etc, input list of triplets
    final String QUERY="INSERT INTO [myTable] (f1,f2,f3) values ";
    LinkedList params=new LinkedList();
    String comma="";
    StringBuilder q=QUERY;
    for(int nl=0; nl< args.length; nl+=3 ) { // args is a list of triplets values
        params.add(args[nl]);
        params.add(args[nl+1]);
        params.add(args[nl+2]);
        q.append(comma+"(?,?,?)");
        comma=",";
    }      
    int nr=insertIntoDB(q, params);
    

    in my DBInterface class I have:

    int insertIntoDB(String query, LinkedList params) {
        preparedUPDStmt = connectionSQL.prepareStatement(query);
        int n=1;
        for(String x:params) {
            preparedUPDStmt.setString(n++, x);
        }
        int updates=preparedUPDStmt.executeUpdate();
        return updates;
    }
    

提交回复
热议问题