我在Servlet中循環查詢時遇到了超時錯誤,因此我決定創建一個只執行一次的長查詢。在循環中自行添加字符串時SQL查詢中的錯誤
下面是代碼:
public void deactivateAccount(String[] userList) {
DBConnectionFactory myFactory = DBConnectionFactory.getInstance();
Connection con = myFactory.getConnection();
try {
con.setAutoCommit(false);
String combinedQueries = "";
for (int i =0; i<userList.length;i++) {
String query = "UPDATE users SET active='0' WHERE userID = ? ; ";
combinedQueries += query;
}
System.out.println(combinedQueries);
PreparedStatement p = con.prepareStatement(combinedQueries);
for (int i =0; i<userList.length;i++) {
int currentNum = i+1;
p.setInt(currentNum, Integer.parseInt(userList[i]));
System.out.println("current num is " + currentNum);
System.out.println("userlist value is " + Integer.parseInt(userList[i]));
}
p.execute();
} catch (SQLException ex) {
try {
con.rollback();
} catch (SQLException ex1) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex1);
}
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
此代碼是在我的DAO - 它的作用是循環需要字符串多次(有多少複選框用戶檢查),然後準備在聲明另一個循環(設置準備語句的參數),然後執行它。
我得到錯誤:
Severe: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE users SET active='0' WHERE userID = 1; UPDATE users SET active='0' WHERE ' at line 1 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
但是當我在執行前打印查詢中的代碼,這是出現什麼:
Info: UPDATE users SET active='0' WHERE userID = ?; UPDATE users SET active='0' WHERE userID = ?; UPDATE users SET active='0' WHERE userID = ?; UPDATE users SET active='0' WHERE userID = ?; (assuming 4 checkboxes were clicked)
該方法接受的陣列,我從一個請求獲得.getParameterValues來自servlet。
預先感謝您的幫助!