user69309 user69309 - 2 years ago 140
Java Question

MySQL Java syntax error

Trying to figure out what the error is in this java code.

The SQLException reads: " 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 'order (item_quantity, customer_id, product_id) VALUES (5, 191, 31)'

The order table looks like

order_id int pk ai <br>
item_quantity <br>
customer_id int <br>
product_id int <br>

And the function that inserts is:

public void createOrder(int productQuantity, int customerId, int productId) throws SQLException {

sql = "INSERT INTO order (item_quantity, customer_id, product_id) VALUES (" + productQuantity + ", " + customerId + ", " + productId + ")";
try {
int a = stmt.executeUpdate(sql);
if (a == 1) {
System.out.println("Order Added");
} else {
System.out.println("Order Failed");
} catch (SQLException e) {

Any help would be greatly appreciated, can't seem to figure this out.

Answer Source

Enclose the order (table name) by backtick like below:

INSERT INTO `order` (item_quantity, customer_id, product_id) VALUES...


The backticks help you from accidentally using a name that is a reserved word in SQL for example. Take a table named "where", it's a stupid name for a table I agree, but if you wrap it in backticks it will work fine

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download