public void actionPerformed(ActionEvent e) { String username=uField.getText().trim(); String password =pField.getText().trim(); String phonenum=tField.getText().trim(); String gender=bg.isSelected(maleBtn.getModel())?maleBtn.getText():femaleBtn.getText(); String Driver = "com.mysql.cj.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/data2?characterEncoding=UTF8&useSSL=false"; Connection conn = null; try{ Class.forName(Driver); conn = DriverManager.getConnection(url, "root", "yxh9497"); Statement stmt=conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM userinformation"); while(rs.next()) { if(username==rs.getString(username)) { JOptionPane.showMessageDialog(null, "用户名已被注册"); break; } } String sql1="insert into userinformation values('"+ username+ "','"+password+"','"+phonenum+"','"+gender+"')"; int a= stmt.executeUpdate(sql1); }catch(Exception ex){ ex.printStackTrace(); } try{ //关闭数据库联接类 conn.close(); }catch(Exception ex){ ex.printStackTrace(); } JOptionPane.showMessageDialog(null, "注册成功"); jf.setVisible(false); new GUI().init();}我想在当用户名重复时,不再执行String sql1="insert into userinformation values('"+ username+ "','"+password+"','"+phonenum+"','"+gender+"')"; int a= stmt.executeUpdate(sql1); }catch(Exception ex){ ex.printStackTrace(); } try{ //关闭数据库联接类 conn.close(); }catch(Exception ex){ ex.printStackTrace(); } JOptionPane.showMessageDialog(null, "注册成功"); jf.setVisible(false); new GUI().init();}这些语句,该怎么办
时间: 2024-03-03 13:48:14 浏览: 199
你可以在 while 循环中加一个标志变量,如 isExist,初始值为 false。如果找到重复的用户名,将该变量设为 true,然后在 while 循环结束后根据 isExist 的值来判断是否执行插入语句和注册成功的提示框。修改后的代码如下:
```
public void actionPerformed(ActionEvent e) {
String username = uField.getText().trim();
String password = pField.getText().trim();
String phonenum = tField.getText().trim();
String gender = bg.isSelected(maleBtn.getModel()) ? maleBtn.getText() : femaleBtn.getText();
String Driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/data2?characterEncoding=UTF8&useSSL=false";
Connection conn = null;
boolean isExist = false; // 标志变量
try {
Class.forName(Driver);
conn = DriverManager.getConnection(url, "root", "yxh9497");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM userinformation");
while (rs.next()) {
if (username.equals(rs.getString("username"))) { // 修改此处
JOptionPane.showMessageDialog(null, "用户名已被注册");
isExist = true; // 修改标志变量的值
break;
}
}
if (!isExist) { // 如果用户名不存在,才执行以下语句
String sql1 = "insert into userinformation values('" + username + "','" + password + "','" + phonenum + "','" + gender + "')";
int a = stmt.executeUpdate(sql1);
JOptionPane.showMessageDialog(null, "注册成功");
jf.setVisible(false);
new GUI().init();
}
} catch (Exception ex) {
ex.printStackTrace();
}
try {
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
```
阅读全文