我正在尝试在我的servlet项目中创建一个注册页面。
如果用户名已被占用,我想显示一条错误消息。
这是我的代码:
String uname=request.getParameter("uname");
String pass=request.getParameter("pass");
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/covid","root","fbfbfb333*");
String query = "SELECT * FROM users WHERE username = ?";
pstmt = (PreparedStatement) con.prepareStatement(query);
pstmt.setString(1, uname);
rs = pstmt.executeQuery();
if(rs.next()) {
PreparedStatement pst = (PreparedStatement) con.prepareStatement(" insert into users(username,password) values(?,?)");
pst.setString(1, uname);
pst.setString(2, pass);
pst.executeUpdate();
response.sendRedirect("login.jsp");
} else {
System.out.println("Username " + uname + " already exists.");
}
} catch (Exception e) {
e.printStackTrace();
}
但是,当我添加新用户时,无论是否存在,它都会说“用户名已被占用”。
我该怎么办?
切换条件,如果有结果集数据表示已使用用户名,则插入新用户名