2011-03-24 108 views
0


我必須使用PreparedStatement在表的字段上創建一個索引。我所要執行的查詢如下:Java PreparedStatement和Alter Table語法錯誤

ALTER TABLE esa_matrix ADD INDEX doc_index (id_doc) 

所以,我創建一個PreparedStatement實例與查詢相同的文字和對其執行executeUpdate()方法。但在執行時,我得到一個SQL語法錯誤。 這是創建PreparedStatement實例:

PreparedStatement ps = conn.prepareStatement("ALTER TABLE "+ESATable+ "ADD INDEX doc_index ("+idDocLabel+")");         
ps.executeUpdate(); 
ps.close(); 

此SQLException我得到:

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 'doc_index (id_doc)' at line 1 

我怎樣才能解決這個問題?
由於提前,
安東尼

+0

我鼓勵你爲這種「stringconstruction」使用String.format()而不僅僅是DB-querys。 'String query = String.format(「ALTER TABLE%s ADD INDEX doc_index(%s)」,ESATable,idDocLabel);' – 2012-10-24 12:21:06

回答

3

你忘了一個空格前的「ADD」。

+0

哦,我不敢相信!謝謝Phill :) – 2011-03-24 09:30:13

+1

容易犯的錯誤,如果我每次都有一磅,我會做一個富人:) – 2011-03-24 10:42:41

+0

另外,因爲它是一個準備好的聲明,你不能使用ps = conn.prepareStatement(「ALTER TABLE?ADD INDEX doc_index?」);然後使用ps.setString(1,「ESATable」)等。不知道它是否允許,但如果是,它肯定會使語句更容易讀取和調試。 – DaveH 2011-03-24 14:34:28