基本上我將一條記錄添加到數據庫:標題和說明。 我想讓它如此,如果標題的值已經存在 - 將(1)或(2)添加到最後以使其可區分。我寫了這個函數:Java:雖然記錄存在=保持將記錄添加到記錄的末尾
public boolean existCheck(int userId, String title){
String Validate = "SELECT COUNT(*) FROM memories WHERE userid='"+userId+"' AND title='"+title+"'";
int cnt = 0;
boolean result = false;
try{
rs = st.executeQuery(Validate);
if(rs.next()){
cnt = rs.getInt(1);
System.out.println(cnt);
if(cnt != 0){
result = true;
}
}
}
catch(Exception e){e.printStackTrace();}
return result;
}
它計算該userID和Title有多少條目。如果不是0,則它存在並返回它存在的真。
此代碼將記錄添加到數據庫。
if(existCheck(userId, title) == true){
st.executeUpdate("INSERT INTO memories (userid, title, description) VALUES ('"+userId+"', '"+title+"(1)', '"+desc+"')");
}
else{
st.executeUpdate("INSERT INTO memories (userid, title, description) VALUES ('"+userId+"', '"+title+"', '"+desc+"')");
}
但這個代碼的缺點是,如果title(1)已經存在,它會再次添加另一個標題(1)。 當然,我可以做很多if語句,但我確信我可以使用while循環以較少的線條做到這一點。
我不知道如何在這種情況下使用它,但我不希望服務器陷入無限循環。
我該如何申請while()循環呢?
這個解決方案的工作,以什麼方式更安全? – arleitiss 2014-12-13 18:51:19
@arleitiss閱讀關於SQL注入 – Eran 2014-12-13 18:52:57