你顯然不會顯示所有相關的代碼,或者你只是忽略了將所需的代碼放入應該使其工作的方法中。
A ResultSet基本上是您的查詢的結果集合,您需要遍歷該結果以訪問該查詢的所有結果。 A 而循環被廣泛用作遍歷結果集對象中包含的所有結果的手段。我在代碼中看不到你已經聲明瞭一個ResultSet對象,但你正在嘗試使用它。也許嘗試是這樣的:
String email = email_register_txt.getText();
String username = username_register_txt.getText();
try {
Connection conn = DriverManager.getConnection("...your jdbc connection string...");
conn.setAutoCommit(false);
String sql = "SELECT * FROM user_profile WHERE username = ? OR user_email = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, email);
ResultSet res = stmt.executeQuery();
// Utilize a boolean Flag to indicate whether
// or not the User is registered.
boolean registered = false;
while (res.next()) {
if(res.getString("username").equalsIgnoreCase(username)) {
JOptionPane.showMessageDialog(registerPanel,
"The username has already been already registered!");
registered = true;
break; // Get out of the loop. No more need for it.
}
else if(res.getString("user_email").equalsIgnoreCase(email)) {
JOptionPane.showMessageDialog(registerPanel,
"This email address has already been already registered!");
registered = true;
break; // Get out of the loop. No more need for it.
}
}
// Do what needs to be done if User is NOT registered.
if (!registered) {
...............................
...............................
}
res.close();
stmt.close();
conn.close(); //Close the DB connection
}
catch (SQLException ex) {
ex.printStackTrace();
}
你會發現使用PreparedStatement類。使用此類有許多好處:
1)PreparedStatement允許您編寫動態參數查詢。
2)PreparedStatement比使用Java中的Statement更快。
3)的PreparedStatement防止SQL注入攻擊在Java中
瞭解更多關於Why to use Prepared Statements in Java here。
而你的問題是...... –
當我輸入一個已經存在的用戶名,它什麼也不做...... –
你確認你的查詢返回任何行嗎? –