2016-04-27 24 views
1

このJavaコードに何が含まれているかを調べようとしています。MySQL Java構文エラー

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()); 
    } 
} 

任意の助けをいただければ幸いですが、これを理解するように見えることはできません。

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

と挿入機能があるよう

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)' 

順序テーブルが見えます。

+0

'order'をバッククックしてください。 – 1000111

+0

[ORDERは予約語です](http://dev.mysql.com/doc/refman/5.0/en/keywords.html)。代わりに ''注文 ''を書いてください。 – Satya

+1

この特定の問題とは関係ありませんが、このようにSQLを実行するのに慣れてくるとすぐに、PreparedStatementsを調べる必要があります。彼らはあなたにより大きなセキュリティを提供します( 'int' argsがStringsの場合、すぐにSQLインジェクション攻撃について疑問に思うでしょう)。 – yshavit

答えて

3

は、以下のようにバッククォート によってため(テーブル名)を囲みます。

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

注:

バッククォートが誤ってSQLの予約語である名前を使用してからあなたを助けます例えば。 "where"という名前のテーブルを取ってください。テーブルの愚かな名前ですが、バックティックでラップすれば正常に動作します。

+0

同じエラーが発生する – user69309

+0

'sql'変数を出力して結果を共有できますか? – 1000111

+0

SQL変数:INSERT INTO 'order'(item_quantity、customer_id、product_id)VALUES(3,211,31) – user69309