2011-03-24 110 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