0

编辑:解决了!多谢你们!: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

4 回答 4

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

于 2013-02-21T20:59:18.617 回答
1

您定义但从不将值分配给:

String username;
String password;

让这个检查工作。

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

您应该在设置值之前usernamepassword

 this.username = rs.getString("username");
 this.password = rs.getString("password");

无论如何,它是不需要的。由于这两个值都在 youWHERE子句中,如果您得到任何结果,则意味着您受到了打击,因此您可以if

 if (rs.next()) {            

注意:您必须删除前一个rs.next()(您将只获得一行用于查询)。

也就是说,有几个提示:

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

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

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

于 2013-02-21T22:36:04.630 回答
0

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

于 2013-02-21T20:58:11.733 回答
-1

我认为你的代码应该是这样的,

rs.next();
            if ((user.equals(rs.getString("username"))) && (pass.equals(rs.getString("password")))) {
                JOptionPane.showMessageDialog(null, "You are now logon!");
            } 
于 2013-02-21T21:00:19.133 回答