为什么rs.next()无法正常工作?

时间:2013-02-21 20:55:43

标签: java mysql oop

编辑:解决了!多谢你们! :d

即使我输入了正确的凭据,我仍然会收到错误showMessageDialog .. 我相信rs.next()将返回一个高于0的值,然后如果用户的凭据与users_table中的凭据匹配,则必须进行限制,但我总是 获取错误消息,就好像凭据不匹配一样。

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                   
}

4 个答案:

答案 0 :(得分:1)

您没有检查rs.next()

的返回值

尝试:

            if (rs.next()) {
                JOptionPane.showMessageDialog(null, "You are now logon!");
            } else {
                JOptionPane.showMessageDialog(null, "damn!", "alert", JOptionPane.ERROR_MESSAGE); 
            }

请参阅: http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#next%28%29

答案 1 :(得分:1)

您定义,但从不为以下内容指定值:

String username;
String password;

要使此检查有效。

 if ((user.equals(username)) && (pass.equals(password))) {

您应该在设置usernamepassword

的值之前
 this.username = rs.getString("username");
 this.password = rs.getString("password");

无论如何都不需要它。由于这两个值都在您WHERE子句中,如果您得到任何结果,则意味着您获得了点击,因此您可以将if更改为

 if (rs.next()) {            

注意:您必须删除之前的rs.next()(查询只能获得一行)。

那说了几个提示:

1)不要存储未加密的密码。存储散列版本(MD-5,SHA-1)。如果重要,请使用盐。这样,可以读取表格的人将无法猜出密码。首先,您可以使用未编辑的表进行测试,当它工作时添加加密。

2)正如其他人所说,你最好使用PreparedStatement

3)除非您经常使用它,否则不要将连接作为实例变量。使其成为使用它的方法的局部变量。并close()正确。这样你就不会占用你的服务器资源。

答案 2 :(得分:0)

你在真空中调用rs.next。您不测试结果或使用结果集数据。

答案 3 :(得分:-1)

我认为您的代码应该是类似的,

rs.next();
            if ((user.equals(rs.getString("username"))) && (pass.equals(rs.getString("password")))) {
                JOptionPane.showMessageDialog(null, "You are now logon!");
            }