2016-04-27 40 views
1

試圖找出這個Java代碼中的錯誤。MySQL Java語法錯誤

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

順序表看起來像

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

這接入功能是:

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

任何幫助將不勝感激,似乎無法想出解決辦法。

+0

請問你可以反請一下'訂單'嗎? – 1000111

+0

[ORDER是一個保留字](http://dev.mysql.com/doc/refman/5.0/en/keywords.html)。寫'Order'而不是'order'。 – Satya

+1

與此特定問題無關,但作爲_soon_,當您開始習慣使用這種SQL方式時,您應該開始查看PreparedStatements。它們爲您提供更高的安全性(如果您的'int'參數是字符串,我會立即想知道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