【问题标题】:Query database for ID and write Name to a variable in Java [closed]查询数据库的 ID 并将名称写入 Java 中的变量 [关闭]
【发布时间】:2015-04-05 09:10:03
【问题描述】:

我正在尝试编写一个带有登录窗口的程序(在 Java 中),我已经成功地进行了登录,但是当用户登录时,我希望程序在数据库中找到他们的名字(使用他们的 ID ) 并将他们的名字写入不同类中的变量(使用登录名初始化)。目的是然后从不同 JFrame 中的变量中检索名称并将其写入标签,从而显示当前用户。
到目前为止,我的代码如下:

public class GUI_Launcher extends javax.swing.JFrame {

private Connection connection;
private Connection getConnection() throws ClassNotFoundException, SQLException {
    if (connection == null) {
        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        String connURL = "jdbc:ucanaccess://"+ new File("databases/Employees.accdb").getAbsolutePath();
        connection = DriverManager.getConnection(connURL, "", "");
    }
    return connection;
}

private boolean validateUser(String STR_UserID, String STR_Password) {
    boolean validation = false;
    try (Statement statement = getConnection().createStatement();){
        try (ResultSet result = statement.executeQuery("SELECT COUNT(*) AS Count FROM Employees WHERE [UserID]='" + STR_UserID.replaceAll("'", "''") + "' AND StrComp([Password],'" + STR_Password.replaceAll("'", "''") + "', 0) = 0 AND [LoginAllowed] = 1" )) {
            if(result != null) {
                result.next();
            }
            validation = result != null && result.getInt(1) > 0;
        }
    } catch (SQLException | ClassNotFoundException e) {
        e.printStackTrace();
    }
    return validation;
}

public GUI_Launcher() {
    SYS_Package.SYS_Vars SYS_Vars = new SYS_Package.SYS_Vars();
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    BTN_Login = new javax.swing.JButton();
    BTN_Cancel = new javax.swing.JButton();
    LBL_UserID = new javax.swing.JLabel();
    LBL_Password = new javax.swing.JLabel();
    FLD_UserID = new javax.swing.JTextField();
    FLD_Password = new javax.swing.JPasswordField();
    LBL_Error = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Login [Main] - Philani Sales");
    setAlwaysOnTop(true);
    setMaximumSize(new java.awt.Dimension(416, 339));
    setMinimumSize(new java.awt.Dimension(416, 339));
    setResizable(false);

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

    BTN_Cancel.setText("Cancel");
    BTN_Cancel.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            BTN_CancelActionPerformed(evt);
        }
    });

    LBL_UserID.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
    LBL_UserID.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    LBL_UserID.setText("User ID");

    LBL_Password.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
    LBL_Password.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    LBL_Password.setText("Password");

    FLD_Password.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            FLD_PasswordKeyPressed(evt);
        }
    });

    LBL_Error.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
    LBL_Error.setForeground(new java.awt.Color(255, 0, 0));

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(LBL_Error, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(BTN_Cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 100, Short.MAX_VALUE)
                    .addComponent(BTN_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(LBL_UserID, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(LBL_Password, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(FLD_UserID)
                        .addComponent(FLD_Password))))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(40, 40, 40)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(FLD_UserID)
                .addComponent(LBL_UserID, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(LBL_Password, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
                .addComponent(FLD_Password))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 86, Short.MAX_VALUE)
            .addComponent(LBL_Error, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(BTN_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(BTN_Cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap())
    );

    setSize(new java.awt.Dimension(416, 339));
    setLocationRelativeTo(null);
}// </editor-fold>                        

private void BTN_CancelActionPerformed(java.awt.event.ActionEvent evt) {                                           
    this.dispose();
}                                          

private void BTN_LoginActionPerformed(java.awt.event.ActionEvent evt) {                                          
    String STR_UserID = FLD_UserID.getText();
    String STR_Password = new String(FLD_Password.getPassword());
    validateUser(STR_UserID, STR_Password);
    if (validateUser(STR_UserID, STR_Password)) {
        GUI_Main GUI_Main = new GUI_Main();
        GUI_Main.setExtendedState(JFrame.MAXIMIZED_BOTH);
        GUI_Main.setUndecorated(true);
        GUI_Main.setVisible(true);
        this.dispose();
    }
    else {
        FLD_UserID.setText("");
        FLD_Password.setText("");
        LBL_Error.setText("Invalid Login Credentials!");
    }
}                                         

private void FLD_PasswordKeyPressed(java.awt.event.KeyEvent evt) {                                        
    if (evt.getKeyCode() == KeyEvent.VK_ENTER){
        BTN_Login.doClick();
    }
}                                       

/**
 * @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(GUI_Launcher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(GUI_Launcher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(GUI_Launcher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(GUI_Launcher.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 GUI_Launcher().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton BTN_Cancel;
private javax.swing.JButton BTN_Login;
private javax.swing.JPasswordField FLD_Password;
private javax.swing.JTextField FLD_UserID;
private javax.swing.JLabel LBL_Error;
private javax.swing.JLabel LBL_Password;
private javax.swing.JLabel LBL_UserID;
// End of variables declaration                   

我对 Java 还很陌生,因此非常感谢您提供一些示例代码以及解释。谢谢。

【问题讨论】:

  • “非常感谢您提供一些示例代码以及解释。” 互联网上有很多“查询数据库”Java 示例。请搜索它们并真正尝试一下。如果您有具体问题,请回复我们。
  • Andrew 到目前为止,我已经花了几天时间搜索互联网,测试来自不同站点的示例,但都无济于事。如果我不需要,我不会在这里浪费人们的时间。
  • “到目前为止花了几天时间搜索互联网” 使用了哪些搜索词?发现最有帮助的 3 个示例是什么?为什么它们没有有帮助?

标签: java database swing


【解决方案1】:

在询问了我的 java-wizard 朋友后解决了这个问题。将以下代码添加到按钮操作处理程序中:

try {
        PreparedStatement STMT_GetCurrentUser = getConnection().prepareStatement("SELECT * FROM Employees WHERE [UserID]='"+STR_UserID+"'");
        ResultSet RSET_GetCurrentUser = STMT_GetCurrentUser.executeQuery();
        if (RSET_GetCurrentUser.next()){
            SYS_Vars.SYS_CurrentUser = RSET_GetCurrentUser.getString(2);
        }
    } catch (SQLException EX_1) {
        EX_1.printStackTrace();
    } catch (ClassNotFoundException EX_2) {
        EX_2.printStackTrace();
    }

回想起来,我显然很愚蠢,因为我没有意识到我必须使用 getConnection() 方法而不是连接,但鉴于我的 Java 背景很少,我并不感到惊讶。

【讨论】:

    猜你喜欢
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多