2013-06-05 152 views
0

需要幫助,請..錯誤插入數據到MySQL表

Connection cn = DriverManager.getConnection ("jdbc:mysql://localhost/posdb", "root", ""); 
    PreparedStatement dat = cn.prepareStatement("INSERT INTO order VALUES('"+num+"',"+buyamount.elementAt(0)+","+buyamount.elementAt(1)+","+buyamount.elementAt(2)+","+buyamount.elementAt(3)+","+buyamount.elementAt(4)+","+buyamount.elementAt(5)+","+buyamount.elementAt(6)+","+buyamount.elementAt(7)+","+buyamount.elementAt(8)+","+buyamount.elementAt(9)+","+buyamount.elementAt(10)+","+buyamount.elementAt(11)+","+buyamount.elementAt(12)+","+buyamount.elementAt(13)+","+buyamount.elementAt(14)+","+buyamount.elementAt(15)+","+buyamount.elementAt(16)+","+buyamount.elementAt(17)+","+buyamount.elementAt(18)+","+buyamount.elementAt(19)+","+tot+","+tot2+","+(tot2-tot)+")"); 
    System.out.println(dat); 
    dat.executeUpdate(); 
    cn.close(); 

錯誤消息:

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('20130605093640',1, 0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9500,1200' at line 1 

num是一個字符串,TOT和tot2是整數,並且buyamount是整數的向量。

感謝..任何幫助將不勝感激..

+0

看一看http://stackoverflow.com/questions/3137910/how-can-i-make-a-table-in-mysql-called-order – Craig

+0

我沒有意識到,訂單一個保留字。非常感謝:) – Aldibe

回答

1

Order是MySQL中的保留字 - 它周圍使用反引號:

INSERT INTO `order`... 

http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

+0

它反引起的反應仍然產生相同的錯誤。但是當我將表格更改爲訂單時,它工作正常。謝謝。 – Aldibe

+0

@ user2453998 - 反引號應該工作(不是單引號)。但是,如果可以的話,我會建議更改表名。真高興你做到了! – sgeddes

0

在您可能要另外考慮使用正確的方式準備好的聲明。這將有助於避免sql注入,並使您的代碼更易於閱讀。

private static final String INSERT = "insert into myTable values(?,?,?)"; 
public void insertData(String varA, int numB, Date myDate) throws SQLException { 

    Connection cn=null; 
    PreparedStatement ps=null; 
    try { 
     cn = DriverManager.getConnection("...your connection string..."); 
     ps = cn.prepareStatement(INSERT); 
     ps.setString(1, varA); 
     ps.setInt(2, numB); 
     ps.setDate(3, myDate); 

     ps.executeUpdate(); 

    }catch(SQLException sqe) { 
     throw sqe; 
    } finally { 
     try {ps.close();}catch(Exception ex) {} 
     try {cn.close();}catch(Exception ex) {} 
    } 
}