Java:whilerecord exists=继续向记录末尾添加数字

Java:whilerecord exists=继续向记录末尾添加数字,java,sql,while-loop,Java,Sql,While Loop,基本上,我正在向数据库添加一条记录:标题和描述。 如果标题的值已经存在,我想这样做-在末尾添加(1)或(2)以使其可区分。我写了这个函数: public boolean existCheck(int userId, String title){ String Validate = "SELECT COUNT(*) FROM memories WHERE userid='"+userId+"' AND title='"+title+"'"; int cnt = 0; boo

基本上,我正在向数据库添加一条记录:标题和描述。 如果标题的值已经存在,我想这样做-在末尾添加(1)或(2)以使其可区分。我写了这个函数:

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;
}
它统计存在多少个具有该用户ID和标题的条目。如果不是0,则它存在,并返回true表示它存在

此代码将记录添加到数据库中

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+"')");    
}
但该代码中的缺陷是,若标题(1)已经存在,它将再次添加另一个标题(1)。 当然,我可以使用很多if语句,但我确信我可以使用while循环使用较少的行

但我不知道如何在这种情况下使用它,我不希望服务器陷入无限循环


如何将while()循环应用于此?

您的
existCheck
应该返回计数而不是布尔值

然后,您可以执行以下操作:

int index = existCheck(userId, title);
if(index > 0){
      st.executeUpdate("INSERT INTO memories (userid, title, description) VALUES ('"+userId+"', '"+title+index+"', '"+desc+"')");
} else{
      st.executeUpdate("INSERT INTO memories (userid, title, description) VALUES ('"+userId+"', '"+title+"', '"+desc+"')");    
}
输入的第一条记录将有
标题
,第二条
标题+“1”
,第三条
标题+“2”
,依此类推

当然,您还必须更改
existCheck
中的WHERE子句,以说明不同的标题:

SELECT COUNT(*) FROM memories WHERE userid='"+userId+"' AND title LIKE '"+title+"'%"

虽然与您的问题不完全相关,但我强烈建议您使用准备好的语句,而不是静态语句(其中参数值是SQL字符串的一部分)。这样会更安全。

您应该更改
existCheck
以模糊地查找标题,而不是:

"SELECT COUNT(*) FROM memories WHERE userid='"+userId+"' AND title='"+title+"'"
如果要查找完全匹配的标题,请使用

"SELECT COUNT(*) FROM memories WHERE userid='"+userId+"' AND title LIKE '"+title+"%'"
它将查找以
title
开头的标题

或者,如果标题开头与前一个标题不匹配,您也可以使用:

"SELECT COUNT(*) FROM memories WHERE userid='"+userId+"' AND ( title='"+title+"' OR title LIKE '"+title+"(%)' )"
注意
%
将匹配括号中的任何内容,因此
标题(soemthing)
也将匹配。
如果您使用的是MySQL,我不确定是否还有其他数据库服务器


至于避免重复插入标题(1),您需要知道符合条件的标题数量,因此只需返回
计数即可:

public int existCount(int userId, String title){
    String Validate = "SELECT COUNT(*) FROM memories WHERE userid='"+userId+"' AND ( title='"+title+"' OR title LIKE '"+title+"(%)' )";
    int cnt = 0;
    try{
        rs = st.executeQuery(Validate);
        if(rs.next()){
           cnt = rs.getInt(1);
           System.out.println(cnt);
        }
    }
    catch(Exception e){
        e.printStackTrace();
    }
    return cnt;
}
// ...
final int count = existCount(userId, title);
if(count > 0){
    final String sql = String.format("INSERT INTO memories (userid, title, description) VALUES ('%d', '%s(%d)', '%s')", userId, title, count, desc);
    st.executeUpdate(sql);
}
else{
    st.executeUpdate("INSERT INTO memories (userid, title, description) VALUES ('"+userId+"', '"+title+"', '"+desc+"')");    
}

@Arletiss阅读了有关SQL注入的内容
In the exisTCheck() function, I will advice you to return the number instead of boolean. The return number will be number appended with the title. Say if you find only title in DB, then return 0. If you find title(1) then with string split get the number and return it. 

 While you are calling existCheck() function to check whether it is present or not, rather then true or false you will get counter. You just need to increment that counter with new value according to your requirement and modify your query. 


The abstract idea is like this....

Function int existCheck()enter code here
{
// Get the data from the db
// Split the string with title 
//if after title no string then return 0
//else return your number

}
// call to existCheck()
int count = existCheck();
//Modify your query with 
  st.executeUpdate("INSERT INTO memories (userid, title, description) VALUES ('"+userId+"', '"+title+"count', '"+desc+"')");