2011-05-12 152 views
0

我有一個問題,我有一個系統來添加用戶,我必須檢查,如果這個用戶之前存在,這樣我不會再添加他,我從數據庫檢索所有名稱到arraylist.I首先檢查如果數組列表是空的,這樣我可以添加用戶否則,如果他的存在與否 這裏是代碼,他將檢查插入數據庫

if(names.size() == 0){ 
     dbstatement.executeUpdate(" 
     insert into users (user_name,user_password,user_type) 
     values ('" + username + "','" + userpassword + "','" + type + "')"); 
     JOptionPane.showMessageDialog(rootPane, "user added successfully"); 
    } 
    else{     
     for (int i = 0; i < names.size(); i++) { 
      if (username.equals(names.get(i))) { 
       JOptionPane.showMessageDialog(rootPane, "Sorry, this name already exist"); 
       break; 
      } 
     } 
     dbstatement.executeUpdate 
     ("insert into users(user_name,user_password,user_type) 
     values ('" + username + "','" + userpassword + "','" + type + "')"); 
    } 

的問題是,當該程序發現了一個名字存在之前,他告訴我並添加他,我知道這個問題的原因,我想知道在哪裏,但如果在裏面的for循環,我想他告訴我用戶存在只是不要再添加它

+0

我知道你沒有指定這個,但考慮你是否需要['upsert'](http://en.wikipedia.org/wiki/Upsert)。 – onedaywhen

回答

1

只需使用SQL WHERE子句查看用戶名是否存在。絕對不需要將整個數據庫表複製到Java內存中。

preparedStatement = connection.prepareStatement("SELECT id FROM users WHERE user_name = ?"); 
preparedStatement.setString(1, username); 
resultSet = preparedStatement.executeQuery(); 
boolean exist = resultSet.next(); 

總結這就像boolean exist(String username)的方法,並重新安排你的代碼流程如下:

if (exist(username)) { 
    // Show warning message. 
} else { 
    // Insert into DB. 
} 

注意PreparedStatement是被用來代替Statement。這可以防止你的代碼從SQL injection attacks

0
if(names.size() == 0){ 
    dbstatement.executeUpdate(" 
    insert into users (user_name,user_password,user_type) 
    values ('" + username + "','" + userpassword + "','" + type + "')"); 
    JOptionPane.showMessageDialog(rootPane, "user added successfully"); 
} 
else{ 
    if (names.contains(username)) {     
      JOptionPane.showMessageDialog(rootPane, "Sorry, this name already exist"); 
    } 
    else { 
      dbstatement.executeUpdate 
      ("insert into users(user_name,user_password,user_type) 
        values ('" + username + "','" + userpassword + "','" + type + "')"); 
    } 
} 
1

只需調用數據庫添加每個名稱即可。

讓sql嘗試插入名稱。它會插入或拋出密鑰違例(假設你對該名稱有一個唯一的約束)。

如果它引發密鑰違規,則知道該名稱已存在於數據庫中。

如果它沒有拋出錯誤,則插入名稱。

讀/決定/寫風格處理不是做這項工作的方式。當另一個進程在讀和寫之間的時間插入一個新名稱時,它仍然可能有問題。這意味着您仍然必須檢查重要的違規行爲。如果你必須檢查重要的違規行爲,那麼你可能會在第一時間做對,並嘗試插入所有的名字。

+0

+1正確的方法。如果OP的方法得到了擴展,他們最終將複製'前端'代碼中的所有數據庫約束,從而增加了在該過程中引入錯誤的風險(接近確定性)。 – onedaywhen