java
  • sql
  • while-loop
  • 2014-12-13 79 views 3 likes 
    3

    基本上我將一條記錄添加到數據庫:標題和說明。 我想讓它如此,如果標題的值已經存在 - 將(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()循環呢?

    回答

    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字符串的一部分)。這會更安全。

    +0

    這個解決方案的工作,以什麼方式更安全? – arleitiss 2014-12-13 18:51:19

    +1

    @arleitiss閱讀關於SQL注入 – Eran 2014-12-13 18:52:57

    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,我不確定其他數據庫服務器。


    至於避免題(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+"')");  
    } 
    
    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+"')"); 
    
    相關問題