1

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) {
        System.out.println(e.getMessage());
    }
}

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

3
  • Could you please backtick the order? Commented Apr 27, 2016 at 4:34
  • ORDER is a reserved word. Write 'Order' instead order. Commented Apr 27, 2016 at 4:39
  • 1
    Unrelated to this specific problem, but as soon as you start getting comfortable with this way of doing SQL, you should start looking into PreparedStatements. They offer you greater security (if your int args were Strings, I would immediately be wondering about a SQL injection attack). Commented Apr 27, 2016 at 4:41

1 Answer 1

3

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

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

Note:

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

Sign up to request clarification or add additional context in comments.

3 Comments

could you print the sql variable and share the result?
sql variable:INSERT INTO 'order' (item_quantity, customer_id, product_id) VALUES (3, 211, 31)
Probably you are not using backtick. Instead you used single quote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.