3

对于学校,我正在开发一个连接到 MySQL 数据库并执行查询的程序,例如 ATM 机。

到目前为止,我已经制作了一个简单的程序,将连接代码放在提交按钮中,但现在我需要支持许多不同的按钮来进行余额查询、提款等。

对于用户输入登录名和 PIN 的初始屏幕,我有以下代码,但我有点迷失了如何在其他按钮下使用此按钮中的变量进行这些查询:

private void bSubmitActionPerformed(java.awt.event.ActionEvent evt) {                                        
    String login = jLogin.getText();
    String pin = jPin.getText();


    try {
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/bankaccount", "root", "password");

        Statement st = (Statement) con.createStatement();
        PreparedStatement ps;
        String sqlCommand;
        ResultSet rs;

        sqlCommand = "SELECT * FROM accounts WHERE loginID= '" + login + "' AND pin='" + pin + "'";

        rs = st.executeQuery(sqlCommand);

        if (rs.next()) {

            do {

                card2.setVisible(true);
                card1.setVisible(false);



            } while (rs.next());
        } else {
            jWarning.setText("please try again");
        }





    } catch (Exception e) {
    }
}
4

1 回答 1

1
    public ResultSet execute(String sqlCommand ){

    ResultSet rs = null;

    try {
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/bankaccount", "root", "password");

        Statement st = (Statement) con.createStatement();
        PreparedStatement ps;


        rs = st.executeQuery(sqlCommand);


    } catch (Exception e) {
    }

    return rs;

}


public void submitButton1(){
     String login = jLogin.getText();
    String pin = jPin.getText();

ResultSet rs = execute("SELECT * FROM accounts WHERE loginID= '" + login + "' AND pin='" + pin + "'");

   /// do whatever with your rs

}

public void submitButton2(){
     String login = jLogin.getText();
    String pin = jPin.getText();

ResultSet rs = execute("more sql");

   /// do whatever with your rs

}

附加更新方法:

public int update(String sqlCommand ){

       int affected_rows = 0;
        try {
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/bankaccount", "root", "password");

            Statement st = (Statement) con.createStatement();                

            affected_rows = st.executeUpdate(sqlCommand);


        } catch (Exception e) {
        }

        return affected_rows;

    }

update 方法也可用于插入和删除。更新状态可能是这样的:

update accounts  
set columnA = "a value",  
columnB = "other value"  
where loginID = 4;
于 2012-05-30T00:28:46.667 回答