1

Here is my query

result = s.executeUpdate("INSERT INTO order " + "VALUES ('" + id.getText() + "','" + name.getText() + "', '" + code.getText() + "','" + price.getText() + "')");

I am getting this exception:

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 'order VALUES (('1'),('1'),( '1'),('1')' at line 1

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
Asif Mehmood
  • 473
  • 3
  • 16
  • 1
    **WARNING**: You've got a [severe SQL injection bug here](http://bobby-tables.com/java.html) so I'd fix that first. Then remove the extra brackets. – tadman Sep 02 '15 at 19:09
  • 1
    possible duplicate of [Syntax error due to using a reserved word as a table or column name in MySQL](http://stackoverflow.com/questions/23446377/syntax-error-due-to-using-a-reserved-word-as-a-table-or-column-name-in-mysql) – AdamMc331 Sep 02 '15 at 19:18

3 Answers3

3

Order is a reserved word -- I wouldn't use it as a table name, but if you are stuck with it, just put back ticks around it. INSERT INTO `order` ...

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
MHardwick
  • 659
  • 3
  • 9
1

You need to use backticks for reserved keywords,

result = s.executeUpdate("INSERT INTO `order` " + "VALUES ('" + id.getText() + "','" + name.getText() + "', '" + code.getText() + "','" + price.getText() + "')");

Also your code is prone to SQL injection. So you need to work on that as well. My suggestion is to use prepared statement to avoid SQL injection.

Also a good read: Preventing SQL Injection in Java

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

Ensure that none of your getters are sending characters that may cause the query be syntactically incorrect. If your getter is returning a reserved character like the following:

reserved = gen-delims / sub-delims

gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"

sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

*Then the statement will not function as intended. This is why sanitation of inputs is important for any statement.

See more on allowed unencoded in query strings: http://www.456bereastreet.com/archive/201008/what_characters_are_allowed_unencoded_in_query_strings/

packapaul
  • 71
  • 5