将gui中的值添加到数据库表中

时间:2013-02-27 08:52:06

标签: java jdbc resultset

我正在尝试更新数据库中的表格,其中我接受学生的费用并保留收到的金额,收到的总金额和付款方式等的记录。 我的代码如下:

private void pay_saveActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String dbUrl = "jdbc:mysql://localhost/hostel";
    String dbClass = "com.mysql.jdbc.Driver";
    PreparedStatement ps1 = null;

    try {
        Class.forName("com.mysql.jdbc.Driver");

            con = DriverManager.getConnection (dbUrl,"root","17121990");
            System.out.println("connected!");

            String firstname=pay_enter_firstname.getText();
            String lastname=pay_enter_lastname.getText();

            String amt=pay_enter_amt.getText();
            int amount=Integer.parseInt(amt);
            String day=pay_enter_date.getText(); 
            String cheque_no=pay_enter_chequeno.getText();
            String mode=pay_enter_mode.getText();
            int totalamount=10000;               
            int bal_amt=totalamount-amount;
            String remark=pay_enter_remark.getText();          
            int id = Integer.parseInt(pay_enter_id.getText());

            Statement stmt = con.createStatement(
                                  ResultSet.TYPE_SCROLL_INSENSITIVE,
                                  ResultSet.CONCUR_UPDATABLE);
            ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");





            if(rs.next())
           {
                stmt = con.createStatement(
                                  ResultSet.TYPE_SCROLL_INSENSITIVE,
                                  ResultSet.CONCUR_UPDATABLE);
                rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");

              while(rs.next())
                {



              int temp =rs.getInt(1);

              if (temp ==id)
              {
                  int amtrecvd2= rs.getInt(2);
                  bal_amt=totalamount- (amtrecvd2+amount);
                  String updt = "UPDATE payment SET Amountreceivd="+(amtrecvd2+amount)+",lastamtreceived="+amount+",dte='"+day+"', balance_amt ="+bal_amt+" WHERE id ="+temp+";" ;
                  Statement stmt1 = con.createStatement();
                  int result = stmt1.executeUpdate(updt);
              }

                }
           }

             if(!rs.next())
            {
                String str=" INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
                   + "cheque_no,balance_amt,totalamount,Remark) VALUES ("+id+",'"+firstname+"','"+lastname+"',"+amount+",'"+day+"',"+amount+",'"+mode+"','"+cheque_no+"',"+ bal_amt+","+totalamount+",'"+remark+"')";
                Statement stmt1=con.createStatement();

                int result=stmt1.executeUpdate(str);
                panel_feesframe.setVisible(false);
            }


               panel_feesframe.setVisible(false);



    con.close();
    }
        catch (ClassNotFoundException | SQLException | NumberFormatException e)
    {
        e.printStackTrace();
    }

}

最初,当我添加新值时,我得到了正确但当我尝试更新现有行时,我得到错误,我正在为主键ID重复输入。

我应该检查什么条件,以便我知道结果集没有特定的id值而新人正在支付费用?

3 个答案:

答案 0 :(得分:1)

这个条件: if(!rs.next()) 正在while循环之外检查。此条件始终为true,即使已进行更新,也会尝试插入记录。 为避免这种情况,我建议使用标志变量。更新发生后,将此标志的值设置为1。 检查它是否已成为1而不是if(!rs.next())并进入内部。

答案 1 :(得分:1)

您的两个if声明正在发生冲突......

// If this is true...
if(rs.next()) {
    // ...
    // Looping till the it's false...
    while(rs.next()) {
        // ....
    }
 }

 // Will mean that this is false...
 if(!rs.next())

您应该使用else

if(rs.next()) {
    // ...
    while(rs.next()) {
        // ....
    }
 } else {...}

<强>更新

经过Aashray的启发性转换(谢谢),我们得出的结论是你的逻辑被破坏了

而不是手动尝试通过匹配id来手动查找记录,让SQL数据库为您完成。

而不是......

ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");

你应该使用......

ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment where id = " + id);

这将返回一个ResultSet,它是空的(不匹配)或(希望)一行。

从那里,调用rs.next()现在可以让您在更新或插入之间进行正确分支。

private void pay_saveActionPerformed(java.awt.event.ActionEvent evt) {
    String dbUrl = "jdbc:mysql://localhost/hostel";
    String dbClass = "com.mysql.jdbc.Driver";
    PreparedStatement ps1 = null;

    try {
        Class.forName("com.mysql.jdbc.Driver");

        con = DriverManager.getConnection(dbUrl, "root", "17121990");
        System.out.println("connected!");

        String firstname = pay_enter_firstname.getText();
        String lastname = pay_enter_lastname.getText();

        String amt = pay_enter_amt.getText();
        int amount = Integer.parseInt(amt);
        String day = pay_enter_date.getText();
        String cheque_no = pay_enter_chequeno.getText();
        String mode = pay_enter_mode.getText();
        int totalamount = 10000;
        int bal_amt = totalamount - amount;
        String remark = pay_enter_remark.getText();
        int id = Integer.parseInt(pay_enter_id.getText());

        Statement stmt = con.createStatement(
                        ResultSet.TYPE_SCROLL_INSENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
        ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment where id = " + id);

        if (rs.next()) {
            int amtrecvd2 = rs.getInt(2);
            bal_amt = totalamount - (amtrecvd2 + amount);
            String updt = "UPDATE payment SET Amountreceivd=" + (amtrecvd2 + amount) + ",lastamtreceived=" + amount + ",dte='" + day + "', balance_amt =" + bal_amt + " WHERE id =" + id + ";";
            Statement stmt1 = con.createStatement();
            int result = stmt1.executeUpdate(updt);
        } else {
            String str = " INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
                            + "cheque_no,balance_amt,totalamount,Remark) VALUES (" + id + ",'" + firstname + "','" + lastname + "'," + amount + ",'" + day + "'," + amount + ",'" + mode + "','" + cheque_no + "'," + bal_amt + "," + totalamount + ",'" + remark + "')";
            Statement stmt1 = con.createStatement();

            int result = stmt1.executeUpdate(str);
            panel_feesframe.setVisible(false);
        }

        panel_feesframe.setVisible(false);

        con.close();
    } catch (ClassNotFoundException | SQLException | NumberFormatException e) {
        e.printStackTrace();
    }

}

答案 2 :(得分:0)

    I think this may help you

private void pay_saveActionPerformed(java.awt.event.ActionEvent evt){
String dbUrl =“jdbc:mysql:// localhost / hostel”; String dbClass =“com.mysql.jdbc.Driver”; PreparedStatement ps1 = null;

尝试{     的Class.forName( “com.mysql.jdbc.Driver”);

    con = DriverManager.getConnection (dbUrl,"root","17121990");
    System.out.println("connected!");

    String firstname=pay_enter_firstname.getText();
    String lastname=pay_enter_lastname.getText();

    String amt=pay_enter_amt.getText();
    int amount=Integer.parseInt(amt);
    String day=pay_enter_date.getText(); 
    String cheque_no=pay_enter_chequeno.getText();
    String mode=pay_enter_mode.getText();
    int totalamount=10000;               
    int bal_amt=totalamount-amount;
    String remark=pay_enter_remark.getText();          
    int id = Integer.parseInt(pay_enter_id.getText());

    Statement stmt = con.createStatement(
                          ResultSet.TYPE_SCROLL_INSENSITIVE,
                          ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");





    if(rs.next())
   {
        stmt = con.createStatement(
                          ResultSet.TYPE_SCROLL_INSENSITIVE,
                          ResultSet.CONCUR_UPDATABLE);
        rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");

      while(rs.next())
        {



      int temp =rs.getInt(1);

      if (temp ==id)
      {
          int amtrecvd2= rs.getInt(2);
          bal_amt=totalamount- (amtrecvd2+amount);
          String updt = "UPDATE payment SET Amountreceivd="+(amtrecvd2+amount)+",lastamtreceived="+amount+",dte='"+day+"', balance_amt ="+bal_amt+" WHERE id ="+temp+";" ;
          Statement stmt1 = con.createStatement();
          int result = stmt1.executeUpdate(updt);
      }

        }
   }
    else
    {
        String str=" INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
           + "cheque_no,balance_amt,totalamount,Remark) VALUES ("+id+",'"+firstname+"','"+lastname+"',"+amount+",'"+day+"',"+amount+",'"+mode+"','"+cheque_no+"',"+ bal_amt+","+totalamount+",'"+remark+"')";
        Statement stmt1=con.createStatement();

        int result=stmt1.executeUpdate(str);
        panel_feesframe.setVisible(false);
    }


       panel_feesframe.setVisible(false);

con.close(); }     catch(ClassNotFoundException | SQLException | NumberFormatException e) {     e.printStackTrace(); }