我正在使用以下预备声明:
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","root");
String query="select ename from ? ";
st=con.prepareStatement(query);
st.setString(1,"emp");
这里我想从UI提供表名,在上面的代码我有硬编码的表名值。当我尝试执行此代码时,我得到以下例外。
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 ''emp' where intensive='1000'' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3515)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3447)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1951)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2101)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2554)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1761)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1912)
at xmlbulkinsertoperation.getConnection.<init>(getConnection.java:42)
at xmlbulkinsertoperation.getConnection.main(getConnection.java:70)
Mar 26, 2012 12:04:30 PM xmlbulkinsertoperation.getConnection <init>
我无法解决这个问题,请帮助我?
由于
答案 0 :(得分:0)
您不能将带有表名的预准备语句作为参数之一。实体(表名/数据库名称/函数名等)无法在预准备语句中进行参数化。
您必须对表名进行硬编码或将其连接到查询中。