更新MySQL数据库中的数据

时间:2017-09-11 01:26:30

标签: java mysql

我想在MySQL数据库中更新数据,例如权重(2.150Kg)。

这是我在NetBeans中使用的代码:

  connectDB();
    try{

        String value1 = txt_search_code.getText();
        String value2 = txt_item_code.getText();
        String value3 = txt_discription.getText();
        String value4 = txt_bin_balance.getText();
        String value5 = txt_date.getText();
        String value6 = txt_issued_quantaty.getText();
        String value7 = txt_issued_inno.getText();
        String value8 = txt_arrived_quantaty.getText();
        String value9 = txt_arrived_inno.getText();
        String value10 = txt_final_bin_balance.getText();

        String sql = "Update tbl_codes set No='"+value1+"',ITEM_CODE='"+value2+"',DISCRIPTION='"+value3+"',PREVIOUS_BIN_BALANCE='"+value4+
                     "',DATE='"+value5+"',ISSUED_QUANTATY='"+value6+"',ISSUED_INVOICE_NO='"+value7+"',ARRIVED_QUANTATY='"+value8+"',ARRIVED_INVOICE_NO='"+value9+"',FINAL_BINCARD_BALANCE='"+value10+"'WHERE No='"+value1+"' ";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.execute();
        JOptionPane.showMessageDialog(null, " Your new records Updated Succsessfully!!");

    }catch(Exception e){

        JOptionPane.showMessageDialog(null,e);
    }

    closeDB();

这是SQL更新声明:

SELECT
`tbl_stock`.`No`,
`tbl_stock`.`ITEM_CODE`,
`tbl_stock`.`DISCRIPTION`,
`tbl_stock`.`PREVIOUS_BIN_BALANCE`,
`tbl_stock`.`DATE`,
`tbl_stock`.`ISSUED_QUANTATY`,
`tbl_stock`.`ISSUED_INVOICE_NO`,
`tbl_stock`.`ARRIVED_QUANTATY`,
`tbl_stock`.`ARRIVED_INVOICE_NO`,
`tbl_stock`.`FINAL_BINCARD_BALANCE`
FROM `db_biling`.`tbl_stock`;

如何更新重量?

1 个答案:

答案 0 :(得分:1)

尝试使用executeUpdate()代替execute()。但是你的代码需要改进很多。检查我的示例代码

String sql = "Update tbl_codes set No= ?,ITEM_CODE=?,DISCRIPTION=?,PREVIOUS_BIN_BALANCE=?
                    ,DATE=?,ISSUED_QUANTATY=?,ISSUED_INVOICE_NO=?,ARRIVED_QUANTATY=?,ARRIVED_INVOICE_NO=?,FINAL_BINCARD_BALANCE=? WHERE No=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, value1);
pstmt.setString(2, value2);
pstmt.setString(3, value3);
pstmt.setString(4, value4);
pstmt.setString(5, value5);
pstmt.setString(6, value6);
pstmt.setString(7, value7);
pstmt.setString(8, value8);
pstmt.setString(9, value9);
pstmt.setString(10, value10);
pstmt.setString(11, value1);
pstmt.executeUpdate();

如果您使用PreparedStatement,请使用?而不是将值连接到SQL中,例如'"+value1+"'。使用?更清晰,更安全。