简体   繁体   English

检查记录是否存在的最佳方法

[英]Best way to check if the record is exist

what is the best way to check if the user is exist 检查用户是否存在的最佳方法是什么

i have wrote this code 我已经写了这段代码

try{
PreparedStatment mPre=conn.preparedStatement(INSERT INTO TABLE VALUES(?,?);
}catch(Exception e)
{
if(e.getMessage().contains("Dublicated"))
{
throw new Exception("user is exist");
}
}finally {
mPre.close();
conn.close();

}

my friends told me that this is stupid query and i should do like this 我的朋友告诉我这是愚蠢的查询,我应该这样做

Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("SELECT COUNT(*) AS total FROM .......");
int cnt = rs.getInt("total");

Your friend is right. 你的朋友是对的。 You can check if row exists by query: 您可以通过查询检查行是否存在:

SELECT EXISTS(SELECT 1 FROM *table* WHERE *something*)

When you are trying to verify if the given username and password exists in your user table, you should use PreparedStatment because it will help you in protecting your application from SQL injection. 当您尝试验证用户表中是否存在给定的用户名和密码时,应使用PreparedStatment,因为它将帮助您保护应用程序免受SQL注入。

But

Inserting a new user to the database is not the right way to do user validation. 将新用户插入数据库不是执行用户验证的正确方法。

You can do something like this example: 您可以执行以下示例:

 String selectSQL = "SELECT * FROM USER_TABLE WHERE USER_ID = ? AND PASSWORD = ?";
 PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
 preparedStatement.setInt(1, 1001);
 preparedStatement.setString(2, "1234");
 ResultSet rs = preparedStatement.executeQuery(selectSQL );
 while (rs.next()) {
     //You will need user information to render dashborad of your web application
     String userid = rs.getString("USER_ID");
     String username = rs.getString("USERNAME");    
 }

Complete code refrence: http://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/ 完整的代码参考: http ://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/

As long as you are trying to insert a row that breaks the unique primary key constraint of database tables AND the exception thrown has a stack trace that contains the word "duplicated" then your code should work fine. 只要您尝试插入打破数据库表的唯一主键约束的行,并且抛出的异常具有包含单词“ duplicated”的堆栈跟踪,那么您的代码就可以正常工作。
But in the unlikely event that the stack trace changes and does NOT contain that word, your code won't work anymore. 但是,在极少数情况下,堆栈跟踪会更改并且不包含该单词,您的代码将无法再使用。
It's more likely that you are trying to insert a row with a unique primary key value but an existing username, which won't give you the error that you hope for. 您更有可能尝试插入具有唯一主键值但现有用户名的行,这不会给您带来您希望的错误。 That's the reason why it would be smarter/safer to retrieve results for that username and count how many results there are. 这就是为什么更智能/更安全地检索该用户名的结果并计算有多少个结果的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM