簡體   English   中英

檢查數據庫是否具有相同的值

[英]Check database if it has same values

晚上好。 下面是我在數據庫中添加項目的代碼

String sql = "Insert into userinfo(firstname,lastname,contactNumber,email,address,username,password,accountType) value (?,?,?,?,?,?,?,?)";
String accountType = (String) jComboBoxAccType.getSelectedItem();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, jTextFieldFistName.getText());
        ps.setString(2, jTextFieldLastName.getText());
        ps.setString(3, jTextFieldContactNumber.getText());
        ps.setString(4, jTextFieldEmail.getText());
        ps.setString(5, jTextFieldAddress.getText());
        ps.setString(6, jTextFieldUsername.getText());
        ps.setString(7, jTextFieldPassword.getText());
        ps.setString(8, accountType);
        ps.execute();

在添加之前,我如何能夠檢查是否已經存在用戶名和密碼?

通常,您希望數據庫自己強制執行此類數據完整性規則。 這樣可以確保數據正確。 您不想在應用程序級別進行檢查,因為這會引入競爭條件(兩個插入基本上同時發生,兩者都驗證表沒有重復,然后都插入相同的值)。

您可以使用唯一約束或唯一索引來保證唯一性(前者使用后者實現)。 這將在插入重復值時產生錯誤。 很容易創建:

alter table userinfo add constraint unq_username_password unique (username, password);

也就是說,通常一個用戶只有一個密碼,所以限制只在用戶名上:

alter table userinfo add constraint unq_username unique (username);

你需要這樣的代碼

PreparedStatement ps=connection.prepareStatement("select 1 from userinfo where username=? and password=?");
ps.setString(1, jTextFieldUsername.getText());
ps.setString(2, jTextFieldPassword.getText());
ps.execute();
if (ps.getResultSet.next()) {
// So, user and password already in database
}
else {
// Insert value...
}

但是,就我而言,在將新用戶添加到數據庫期間檢查現有的同一對(用戶名、密碼)並不是一個好主意。

有 3 種不同的方法來執行檢查:

1) 創建一個查詢,搜索是否存在具有相同用戶名和密碼的記錄,例如:

SELECT COUNT(*) as exists FROM userinfo WHERE username = :username AND password = :password

或者

SELECT username as exists FROM userinfo WHERE username = :username AND password = :password

因此,如果發現重復記錄,“exists”字段將返回一個不同於 0 或 NULL 的值。

2)只需為用戶名和密碼創建一個唯一索引,當您嘗試插入重復記錄時,將引發錯誤,因此您必須在“ps.execute”之間使用“try...catch”語句”。

3) 添加一個檢查是否存在重復值的子查詢(參見: https : //stackoverflow.com/a/3025332/1641558

您應該只將查詢更改為,

Insert ignore into userinfo(firstname,lastname,contactNumber,email,address,username,password,accountType) value (?,?,?,?,?,?,?,?)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM