下面的代碼的問題是,假設如果查詢[]數組中的特定查詢包含錯誤,語句查詢將執行並且將拋出具有錯誤的查詢的異常,如果兩個查詢都是無錯誤的,或者其他都不應該執行,那麼希望兩個查詢都能被執行,那麼我應該如何處理下面的代碼以獲得期望的結果?請幫助。在Java中的addBatch()執行
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int rw = jTable1.getRowCount();
int col = jTable1.getColumnCount();
System.out.println("RC" + rw);
System.out.println("Col" + col);
String queries[] = new String[rw];
Object o[][] = new Object[rw][col];
String poid = jComboBox10.getSelectedItem().toString();
java.sql.Date xdate = null;
Connection con=null;
Statement st=null;
String cc = ims.MainWindow.cc;
try {
for (int i = 0; i < rw; i++) {
for (int j = 0; j < col; j++) {
o[i][j] = jTable1.getValueAt(i, j);
System.out.println("imj" + i + "," + j + "=" + o[i][j]);
}
if (String.valueOf(o[i][5]) == "") {
xdate=null;
}
else {
xdate = new java.sql.Date(df.parse(String.valueOf(o[i][5])).getTime());
}
queries[i] = "insert into po_items values('" + poid + "','" + cc + "','" + o[i][1] + "'," + o[i][2] + "," + o[i][4] + ",'" + xdate + "','" + o[i][7] + "'," + o[i][8] + ")";
}
for (int k = 0; k < rw; k++) {
System.out.println(queries[k]);
}
String query = "insert into tablex values('xx','yy')";
con=CPool.getConnection();
st=con.createStatement();
con.setAutoCommit(false);
for(int l=0;l<rw;l++)
{
st.addBatch(queries[l]);
}
st.addBatch(query);
st.executeBatch();
con.commit();
System.out.println(query);
} catch (Exception x) {
System.out.println(x.getMessage());
}
finally {
CPool.closeConnection(con);
CPool.closeStatement(st);
}
}
**警告:**您的代碼容易受到[SQL注入攻擊](https://en.wikipedia.org/wiki/SQL_injection)的影響。爲了避免這個漏洞(並獲得一些額外的好處),使用準備好的語句並使用'set *'方法設置參數。 –