我在数据库中已经在mysql建好了若干个表,String数组存储表名
String []column={"titles","classes","levels","teacher","loginSystem","plan","selection"};
现在想删除里面的所有数据,想到的当然是
delete from name
之后我写了一个函数
public void deleteAllValues() throws Exception
{
pstatement=connection.prepareStatement("delete from ?");
for(int i=0;i<column.length;i++)
{
pstatement.setString(1, column[i]);
pstatement.executeUpdate();
}
}
我的pstatement已经在字段中定义为PreparedStatement引用;数据库连接也没有问题,但是执行的时候出错:
Exception in thread "main" 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 ''titles'' 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:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2734)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at ui.LoadData.deleteAllValues(LoadData.java:116)
at ui.LoadData.main(LoadData.java:123)
之后我用statement尝试,获得成功:
public void deleteAllValues() throws Exception
{
Statement statement=connection.createStatement();
for(int i=0;i<column.length;i++)
{
statement.executeUpdate("delete from "+column[i]);
}
}
请高手指点为什么?
------解决方案--------------------------------------------------------
pstmt的表名需要加单引号?
st的不需要加?
第一次听说。
我也第一次见到....从错误上看是''titles''多了引号 语法错误....
st 直接 'delete from xxx' 就可以不报错..