Java:记录存在=继续在记录末尾添加数字

时间:2014-12-13 18:29:02

标签: 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;
    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,那么它就存在并返回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+"')");    
}

但是这段代码中的缺陷是如果title(1)已经存在,它将再次添加另一个标题(1)。 当然我可以编写很多if语句,但我相信我可以使用while循环使用较小的行来完成它。

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

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

3 个答案:

答案 0 :(得分:2)

你的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+"')");    
}

输入的第一条记录为title,第二条title+"1",第三条title+"2",依此类推......

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

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

虽然与你所要求的内容并不完全相关,但我强烈建议您使用预准备语句而不是静态语句(其中参数值是SQL字符串的一部分)。它会更安全。

答案 1 :(得分:1)

您应该更改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+"(%)' )"

注意%会匹配括号中的任何内容,因此title(soemthing)也会匹配。
如果您正在使用MySQL you can use regular expressions,我对其他数据库服务器不确定。


至于避免重复插入 title(1),您需要知道符合条件的标题数量,所以只需返回COUNT

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+"')");    
}

答案 2 :(得分:0)

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+"')");