-4

Here is the code:

String sqlstatment = "INSERT INTO order (orderedBy, totalItems, totalPrice) "+
            "VALUES (?, ?, ?);";


    ResultSet keys = null;

    try (
            PreparedStatement stmt = conn.prepareStatement(sqlstatment, Statement.RETURN_GENERATED_KEYS);
            ){

        stmt.setInt(1, 1);
        stmt.setInt(2, 3);
        stmt.setInt(3, 5);

        int affected = stmt.executeUpdate();

        if (affected == 1){
            keys = stmt.getGeneratedKeys();
            keys.next();
            int newKey = keys.getInt(1);
            orderBean.setOrderID(newKey);
        }else{
            System.out.println("An Error has ocurred while creating the Order.");
        }
    }catch (SQLException e){
        System.err.println(e.getMessage());
    }finally{
        if (keys != null) keys.close();
    }

And when I run the code I get this error:

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 (orderedBy, totalItems, totalPrice) VALUES (1, 3, 5)' at line 1

I'm not entirely sure why I get the error so if you know that would be great.

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
23214asdasd
  • 13
  • 1
  • 4

2 Answers2

1

order is a reserved word, try

String sqlstatment = "INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) "+
            "VALUES (?, ?, ?);";
Turo
  • 4,724
  • 2
  • 14
  • 27
0

Your query contains a RESERVED KEYWORD order as your table name. MySQL documentation clearly suggests that use of such keywords should always be avoided, if they need to be used then it has to be with the use of backticks as shown below '`'.

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

Your query that gets assigned to a String in turn should be changed to the following to resolve this error!

"INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) VALUES (?, ?, ?);"

The following is a documentation link to the reserved keywords for MySQL -> Documentation

Hope this helps!

Community
  • 1
  • 1
N00b Pr0grammer
  • 4,503
  • 5
  • 32
  • 46