简体   繁体   中英

How do I subtract an input from jtextfield to mysql database?

How do i subract an input from mysql database? Let's say I'm doing a bill and inventory system. So when the user input a quantity on a jtextfield, it'd minus off from the table. will attach the GUI.

right now, i have written this method

    public boolean updateBill(Bill bi) {
    boolean success = false;
    dbController db = new dbController();
    PreparedStatement ps;

    try {

        myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ooadp?useSSL=false", "root", "pass"); 

        Statement myStatement = myConn.createStatement();

        String sql = "UPDATE medicalproduct SET  quantity =  quantity - ? WHERE productID = ?, productName = ?, dosage = ?, price = ?, status = ?" ;

        myStatement.executeUpdate(sql);



        myConn.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return success;

}

but then I do not know what to write on my actionPerform and how to link my jtextfield to the sql query.

This is how my gui looks like

Your sql statement is invalid anyway... But if am right, all you want to do is subtract from a field in the database by the value specified in a jTextField

//For example quantity -= txtfieldValue;

If does what you want. You can query for the value of the field, do the subtraction and then finally update the field. Here is an example for updating only the quantity:

public void updateQuantity(String txtFieldValue,String id) throws ClassNotFoundException, SQLException{
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver loaded!!!");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ooadp?useSSL=false", "root", "pass");
        System.out.println("Connection  created!!!");

        PreparedStatement pState;

        String sqlRawP1 ="select quantity from medicalproduct  where productID=?";//I guess medicalproduct is your table name
        pState = conn.prepareStatement(sqlRawP1);
        pState.setString(1, id);
        ResultSet rSetQuantity = pState.executeQuery();

        int countQuantity = 0;
        while(rSetQuantity.next()){
            countQuantity = rSetQuantity.getInt(1);//Am assumming that quantity is an integer
        }

        int value = Interger.parseInt(txtFieldValue);

        countQuantity-= value;

        String sqlRawP2 = "update medicalproduct set quantity=? where productID=?";
        pState = conn.prepareStatement(sqlRawP2);
        pState.setInt(1,countQuantity);
        pState.setString(2, id);

        pState.executeUpdate();

}

Hope it will work well..Forgive me if there are minor errors because I haven't tested it myself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM