Databases Reference
In-Depth Information
System.out.println("Statement " + i +": Unknown number of rows
updated");
else
System.out.println("Statement " + i +": Successful "+ numUpdates[i]
+"rows updated");
}
con.commit();
PreparedStatement and CallableStatement can also be used to make the batch
updates. This can be done by running the same PreparedStatement or
CallableStatement with different parameter values.
Example 5-12 gives the code snippet from the application code from the method
createCart . The method takes an HashMap object which has the key-value pair of
product name and the quantity as an input and inserts the PID and QUANTITY
values using a batch update into a table. The table is also created in the same
method. The name of the table is generated by appending the CID value to the
word cart.
Example 5-12 Batch update with PreparedStatement object
Statement stmt=con.createStatement();
String cart = "cart"+cid;
String insertQuery="insert into "+cart+ " values((select pid
from product where name=?),?)";
String createQuery="create table "+cart+"(pid varchar(10),
quantity int)";
PreparedStatement pstmt=con.prepareStatement(insertQuery);
System.out.println(insertQuery);
stmt.executeUpdate(createQuery);
con.setAutoCommit(false);
Set set=hm.keySet();
Iterator it=set.iterator();
while(it.hasNext())
{
String key=(String) it.next();
pstmt.setString(1,key);
pstmt.setInt(2,((Integer)hm.get(key)).intValue());
pstmt.addBatch();
System.out.println(key +"
"+((Integer)hm.get(key)).intValue());
}
pstmt.executeBatch();
Search WWH ::




Custom Search