首页 > 代码库 > JDBC预编译语句表名占位异常

JDBC预编译语句表名占位异常

有时候,我们有这样的需求,需要清空多个表的内容,这样我们有两种做法,可用delete from table 或 truncate table table,两种方法视情况而定,前者只是一条条的删除表数据,主键自增的序列还能保存,后者类似是重新建表保留表结构,主键信息,也被清空。

OK,下面我们用JDBC开始删除,因为是多个表,所以要循环删除,根据以往的经验,使用预编译的sql语句,可能执行效率会更高,短短几行代码,搞定:

 

public void clearTables()throws Exception{
		String table[]={"person","student"};
		Connection con=this.getConnection();
		String sql="truncate table ? ";

		PreparedStatement ps=con.prepareStatement(sql);
		for(String t : table){
			ps.setString(1, t);
			ps.executeUpdate();	
		}
		System.out.println("清空表完毕");	
	}

运行之后,报如下异常:

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 ‘table ‘td_analysis_ebay_result‘‘ at line 1
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
	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:1054)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4190)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4122)
	at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
	at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
	at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2818)
	at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2157)
	at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2460)
	at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2377)
	at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2361)
	at com.db.DBHelper.clearTable1(DBHelper.java:82)
	at com.db.DBHelper.main(DBHelper.java:155)

异常提示是语法有问题,但仅从表面上看去,写法并没有问题,经查阅,发现动态绑定,是不支持表名绑定的,无论select,delete还是update语句,使用预编译绑定都会发生语法错误,而字段的动态绑定是支持的,既然,不支持,那么就只能用拼接的做法,来清空多个表内容了,代码如下:

public void clearTable()throws Exception{
		String table[]={"a","b"};
		Connection con=this.getConnection();
		for(String t : table){
			String sql="truncate table "+t;
			PreparedStatement ps=con.prepareStatement(sql);
			ps.executeUpdate();	
		}
		System.out.println("清空表完毕");	
	}

运行结果正常。

JDBC预编译语句表名占位异常