private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        Connection conn=DBUtil.getConnection();
        Statement stmt=null;
        try{
            stmt=conn.createStatement();
            String sql="select * from user";
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
        if(jTextField1.getText().equals(rs.getString("username"))){ 
                     JOptionPane.showMessageDialog(null,"该用户名已经存在,不可以使用。");
                 }else if(jTextField1.getText().equals("")){
                     JOptionPane.showMessageDialog(null,"用户名不能为空,请重新填写!");
                 }else if(!jTextField1.getText().equals(rs.getString("username"))){
                      JOptionPane.showMessageDialog(null,"该用户名不存在,可以使用。");
                      }
           }        }catch(SQLException e){
            e.printStackTrace();
        }finally{
        try{
        stmt.close();
        DBUtil.close(conn);
        }catch(SQLException e){
            e.printStackTrace();
        }
      }
    }
这里的while语句对信息提示框(出现次数)有影响,能不能改成别的语句来实现?

解决方案 »

  1.   


    String username = jTextField1.getText();
    if(username.equals(""))
        JOptionPane.showMessageDialog(null,"用户名不能为空,请重新填写!");
    else{
        String sql="select * from user where username='"+username+"'";
        ResultSet rs = stmt.executeQuery(sql);
        if(rs.next())
           JOptionPane.showMessageDialog(null,"该用户名已经存在,不可以使用。");
        else
           JOptionPane.showMessageDialog(null,"该用户名不存在,可以使用。");
    }//手写代码,未测试