我有一个问题,我有一个添加用户的系统,我必须检查这个用户之前是否存在,这样我就不会再次添加他,我从数据库中检索所有名称到一个数组列表中。我首先检查是否数组列表为空,以便我可以添加用户,否则他将检查他是否存在 这是代码
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 循环内的 if 之外,我希望他告诉我用户仅存在,不能再次添加
最佳答案
只需使用 SQL WHERE
子句即可查看用户名是否存在。完全没有必要将整个 DB 表复制到 Java 内存中。
preparedStatement = connection.prepareStatement("SELECT id FROM users WHERE user_name = ?");
preparedStatement.setString(1, username);
resultSet = preparedStatement.executeQuery();
boolean exist = resultSet.next();
将其包装在诸如 boolean exit(String username)
之类的方法中,并按如下方式重新排列代码流程:
if (exist(username)) {
// Show warning message.
} else {
// Insert into DB.
}
请注意PreparedStatement
被用来代替Statement
。这可以防止您的代码 SQL injection attacks .
关于java - 插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5985724/