简体   繁体   中英

Batch update versus IN (x,x,x)

I need to create an update of a field to a list of ids. This list is variable in size.

What I'm wondering is, what of the next two possible options is better:

Option 1: Batch Update:

PreparedStatement update = connection.prepareStatement(" UPDATE table set field = value where id = ?");
for (id : ids){
    update.setInt(id);
    update.addBatch();
}
update.executeBatch();

Option 2: IN (x,x,x)

PreparedStatement list_update = connection.prepareStatement( "UPDATE table set field = value where id in ( " + comma_separated_ids(ids) + ")" );

private String comma_separated_ids(int[] ids){
     // receives [1,2,3] and returns "1,2,3"
}

I'm more inclined towards the second, but I don't like the where id in ( " + comma_separated_ids(ids) + ")" ); because of possible SQL Injection.

So, what option is better? Number 1 or number 2. If number 2 were the case, how could I avoid SQL Injection?

Option 1 is quite more elegant, but with Option 2 you will have better performance (even more if the number of parameters turns big at some point). Just add as many ? as IN parameters needed...then loop again and set them. Do not set the values as-is in the IN clause, use the parametrized fashion (the thing with ? ).

Even having two loops that will be (way!) faster than executing the same number of queries against the database. Moreover, although it is true that if you are using a PreparedStatement you will be executing all queries in the batch in one-go, the database server will executing as many UPDATE queries as number of batch statements you built. Another point is transaction , it's up to you if you decide all or nothing , but that will add some more time on top of that anyway. You can always measure both solutions.

NOTE: I've seen many answers here in StackOverflow where they state that several ? doesn't works as parameters on IN clauses...that's not true, at least for: DB2, Oracle and MySQL using JDBC 4.0. It does works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM