简体   繁体   中英

Mysql Java update column from jtextfield

How to update a field in my database from a JTextField using java?

  • My field in the data base: total
  • My field in java: add_quantity

I need to add the quantity to the total, using sql.

total = total + add_quantity

I tried this:

String value1 = jTextField5.getText();       
PreparedStatement pst = cn.prepareStatement("UPDATE Capitales_totales SET capital_total = $capital_total + '"+value1+"';

What is the correct syntax for doing that?

Your question isn't very clear, datatype of the capital_total isn't provided. So, we'll assume that it's integer or numeric datatype.

MySQL syntax to add a value to the value that's already stored in a column, is something like this:

  UPDATE mytable 
     SET mycol = mycol + 20
   WHERE id = 1

If mycol contains a NULL value, then a NULL will be assigned. (An unknown value plus 20 results in an unknown value.) If you want to handle a NULL value as if it were zero...

  UPDATE mytable 
     SET mycol = IFNULL(mycol,0) + 20
   WHERE id = 1

As far as how you do that in Java prepared statement, use a bind placeholder in place of the value in the SQL text, and then provide a value for the bind placeholder with the setString method.

String sql = "UPDATE mytable
                 SET mycol = IFNULL(mycol,0) + ?
               WHERE id = 1";
PreparedStmt pst = cn.prepareStatement(sql);
pst.setString(1, value1);

sample code snippet for the use-case:

PreparedStatement pst = cn.prepareStatement("Update  Capitales_totales set capital_total =capital_total+?");
pst.setString(1, Integer.parseInt("int_string"));

OR

pst.setInt(1, 1001); //sample int 1001

Try using binds, eg

PreparedStatement pst = cn.prepareStatement("UPDATE Capitales_totales SET capital_total = capital_total + ?");
pst.setInt(1, Integer.parseInt(value1));

Note: Integer.parseInt() may throw RuntimeExpection

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