Java 为什么rs.next()不能正常工作?

Java 为什么rs.next()不能正常工作?,java,mysql,oop,Java,Mysql,Oop,编辑:解决了!谢谢你们D 即使使用正确的凭据键入,仍会出现错误showMessageDialog。。 我相信rs.next()将返回一个大于0的值,然后它必须确认用户的凭据是否与users_表中的凭据匹配,但我始终 获取错误消息,就好像凭据不匹配一样 import java.sql.*; import javax.swing.*; public class System extends javax.swing.JFrame { // variables needed for db c

编辑:解决了!谢谢你们D

即使使用正确的凭据键入,仍会出现错误showMessageDialog。。 我相信rs.next()将返回一个大于0的值,然后它必须确认用户的凭据是否与users_表中的凭据匹配,但我始终 获取错误消息,就好像凭据不匹配一样

import java.sql.*;
import javax.swing.*;

public class System extends javax.swing.JFrame {

    // variables needed for db connection
    Connection conn;
    Statement stmt;
    ResultSet rs;
    String sql;
    String user;
    char[] pass;
    //for table row count
    int ctr = 0;
    //temporary variables needed in retrieving and inserting records  in our db
    int user_id;
    String username;
    String password;

    public System() {
        initComponents();
        setLocationRelativeTo(null);
        dbConnect();
    }

    public void dbConnect() {
        conn = null;
        String url = "jdbc:mysql://localhost:3306/item_db";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "";
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url, userName, password);

            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
            sql = "Select * from users_table";
            rs = stmt.executeQuery(sql);//rs - will hold the records from the databa sql = "Select * from item_table";se

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, e.getMessage());
        }
    }

    private void login() {

        try {
            if (user != null && pass != null) {
                sql = "Select * from users_table Where username='" + user + "' and password='" + pass + "'";
                rs = stmt.executeQuery(sql);

                rs.next();
                if ((user.equals(username)) && (pass.equals(password))) {
                    JOptionPane.showMessageDialog(null, "You are now logon!");
                } 
                else {
                    JOptionPane.showMessageDialog(null, "damn!", "alert", JOptionPane.ERROR_MESSAGE); 
                }
            }
        } catch (SQLException err) {
            JOptionPane.showMessageDialog(this, err.getMessage());
        }

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPasswordField1 = new javax.swing.JPasswordField();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
        jLabel1.setText("Username:");

        jLabel2.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
        jLabel2.setText("Password:");

        jButton1.setText("Login");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancel");

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/login.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(46, 46, 46)
                        .addComponent(jLabel3))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(82, 82, 82)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel1))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField1)
                                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(51, 51, 51)
                                .addComponent(jButton1)
                                .addGap(28, 28, 28)
                                .addComponent(jButton2)))))
                .addContainerGap(52, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(29, 29, 29))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:

        //str = JOptionPane.showInputDialog(this, "Enter id number: ");
        user = jTextField1.getText();
        pass = jPasswordField1.getPassword();
        login();
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(System.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(System.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(System.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(System.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new System().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}
import java.sql.*;
导入javax.swing.*;
公共类系统扩展了javax.swing.JFrame{
//数据库连接所需的变量
连接接头;
报表stmt;
结果集rs;
字符串sql;
字符串用户;
字符[]通过;
//用于表行计数
int ctr=0;
//在数据库中检索和插入记录时需要临时变量
int用户标识;
字符串用户名;
字符串密码;
公共系统(){
初始化组件();
setLocationRelativeTo(空);
dbConnect();
}
公共void dbConnect(){
conn=null;
String url=“jdbc:mysql://localhost:3306/item_db";
String driver=“com.mysql.jdbc.driver”;
字符串userName=“root”;
字符串密码=”;
试一试{
Class.forName(driver.newInstance();
conn=DriverManager.getConnection(url、用户名、密码);
stmt=conn.createStatement(ResultSet.TYPE\u SCROLL\u不敏感,ResultSet.CONCUR\u可更新);
sql=“从用户表中选择*”;
rs=stmt.executeQuery(sql);//rs-将保存数据库中的记录a sql=“Select*from item_table”se
}捕获(例外e){
showMessageDialog(这个,例如getMessage());
}
}
私有void登录(){
试一试{
if(user!=null&&pass!=null){
sql=“从users_表中选择*,其中username='“+user+”,password='“+pass+”;
rs=stmt.executeQuery(sql);
rs.next();
if((user.equals(username))&&(pass.equals(password))){
showMessageDialog(null,“您现在正在登录!”);
} 
否则{
showMessageDialog(null,“该死!”,“警报”,JOptionPane.ERROR\u消息);
}
}
}捕获(SQLException错误){
showMessageDialog(this,err.getMessage());
}
}
@抑制警告(“未选中”)
//                           
私有组件(){
jLabel1=newjavax.swing.JLabel();
jLabel2=newjavax.swing.JLabel();
jTextField1=newjavax.swing.JTextField();
jButton1=newjavax.swing.JButton();
jButton2=newjavax.swing.JButton();
jPasswordField1=newjavax.swing.JPasswordField();
jLabel3=newjavax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(新的java.awt.Font(“Calibri”,0,18));//NOI18N
jLabel1.setText(“用户名:”);
setFont(新的java.awt.Font(“Calibri”,0,18));//NOI18N
jLabel2.setText(“密码:”);
jButton1.setText(“登录”);
jButton1.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
jButton1ActionPerformed(evt);
}
});
jButton2.setText(“取消”);
jLabel3.setIcon(新的javax.swing.ImageIcon(getClass().getResource(“/login.png”);//NOI18N
javax.swing.GroupLayout=newjavax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(46,46,46)
.addComponent(jLabel3))
.addGroup(layout.createSequentialGroup()
.addGap(82,82,82)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.training)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,false)
.addComponent(jTextField1)
.addComponent(jPasswordField1,javax.swing.GroupLayout.PREFERRED_SIZE,134,javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(51,51,51)
.addComponent(jButton1)
.addGap(28,28,28)
.addComponent(jButton2(()()))
.addContainerGap(52,简称最大值))
);
layout.setVerticalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,layout.createSequentialGroup()
.addComponent(jLabel3,javax.swing.GroupLayout.DEFAULT\u SIZE,100,Short.MAX\u值)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1,javax.swing.GroupLayout.PREFERRE
            if (rs.next()) {
                JOptionPane.showMessageDialog(null, "You are now logon!");
            } else {
                JOptionPane.showMessageDialog(null, "damn!", "alert", JOptionPane.ERROR_MESSAGE); 
            }
rs.next();
            if ((user.equals(rs.getString("username"))) && (pass.equals(rs.getString("password")))) {
                JOptionPane.showMessageDialog(null, "You are now logon!");
            } 
String username;
String password;
 if ((user.equals(username)) && (pass.equals(password))) {
 this.username = rs.getString("username");
 this.password = rs.getString("password");
 if (rs.next()) {