Connection conn = /* Connectionオブジェクト */
String query = /* SQL文 */
List paramsList = /* パラメータのリスト(ListのListかObject[]のリスト) */
PreparedStatement st = null;
try {
conn.setAutoCommit(false);
st = conn.prepareStatement(query);
for(int i=0; i<paramsList.size(); i++){
Object obj = paramsList.get(i);
if(obj instanceof List){
List e = (List) obj;
for(int j=0; j<e.size(); j++){
st.setObject(j+1, e.get(j));
}
} else if(obj instanceof Object[]){
Object[] e = (Object[]) obj;
for(int j=0; j<e.length; j++){
st.setObject(j+1, e[j]);
}
}
st.addBatch();
}
int [] numUpdates = st.executeBatch();
for (int i=0; i < numUpdates.length; i++) {
if (numUpdates[i] == -2) {
System.out.println("Row " + i
+ ": unknown number of rows updated");
} else {
System.out.println("Row " + i + " successful: "
+ numUpdates[i] + " rows updated");
}
}
conn.commit();
} catch(BatchUpdateException ex) {
if(conn != null && ! conn.isClosed()){
conn.rollback();
}
ex.printStackTrace();
} catch(SQLException ex){
if(conn != null && ! conn.isClosed()){
conn.rollback();
}
ex.printStackTrace();
} finally {
if(st != null){
st.close();
}
if(conn != null && ! conn.isClosed()){
conn.close();
}
}
|