I have a Java program that connects to a SQL Server 2008 database and performs modifications. If I have a million records I would like to modify, is it bad practice to do as follows:
for(all of the records I need to modify) {
PreparedStatement pst = conn.prepareStatement(someQuery);
// set record specific parameters for pst
// execute pst
}
Or should I build a single query and execute it? Will it make a difference? Does it depend on whether it is an UPDATE, INSERT, or DELETE? My SQL knowledge is quite basic.
For large amounts of UPDATEs, it is best to use
Statement.executeBatch().Try Google’ing for “java executebatch example” for examples.
You will most likely want to also make sure you use Transactions properly, a lot of the overhead of queries come from implicit Transaction (one for every query) where using a single Transaction for many statements can be much more efficient.