Stanley Mungai
Stanley Mungai

Reputation: 4150

Mysql database Error while updating a field

Iam using a Java Swing Application to Update a column in Mysql table. Here is My code(part)

String qunty = txtWithdraw.getText();
String partno = txtNo.getText();
int qty = Integer.parseInt(qunty);
con = DriverManager.getConnection(url + db, "username", "password");
        Statement st = con.createStatement();
String sell = "update Store_info_table set qnty_received = qnty_received - " + qty +      "where Part_number = '" + partno + "'";
                st.executeUpdate(sell);

I am getting the Exception that:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Part_number = 'DF6534'' at line 1

I want to Update the qnty_received field so that it is equal to the Original value minus the value passed by the user i.e (int qty). What Error Am I making?

Upvotes: 1

Views: 148

Answers (2)

davidmontoyago
davidmontoyago

Reputation: 1833

Add a space before the where:

 " where Part_number = '" + partno + "'";

As a good practice, I recommend you to use PreparedStatement and set your parameters with the same. Concatenating the parameters dynamically may force the db engine to parse a new SQL statement every time.

A SQL statement is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

See: PreparedStatement

Upvotes: 6

Marc B
Marc B

Reputation: 360762

Missing space:

... + qty +      "where ...
                  ^--- here

which makes your query something like

... qnty_received - blahwhere

Upvotes: 3

Related Questions