开发者

my Java codes generates a query --> delete from 'emp' , but i need it as--> delete from emp. Please help me

my Java codes generates a query --> delete from 'emp' , but i need it as--> delete from emp. Please help me

void deleteData(Map records) throws SQLException { 
   String delQuery = "delete from ? where empid = ?" 
   String tbname = String records.get(tabName); 
 开发者_如何学C  String empid = String records.get(empid); 
   PreparedStatement data = getPreparedStatement(DelQuery); 
   data.setString(1,tbname); 
   data.setString(2,empid); 
   System.out.println("Query is ---->"+data.toString()); 
   ResultSet rst = data.executeQuery();
 }

when i see the console for errors , it shows :

Query is ----> DELETE FROM 'emp' WHERE empid = '21'

Could not execute sql command - Original message: null


You cannot set a table name as a parameter unfortunately. You have to code it in as part of the SQL.

delQuery = "DELETE FROM " + tbname + " WHERE empid = ?"

Obviously the usual caveats about ensuring your table name fields are sanitized apply.


You can't bind table names with PreparedStatement, only column values. You can do:

...
String tbname = String records.get(tabName);    
String delQuery = "delete from " + tbname + " where empid = ?";
...

This won't make it any more vulnerable to injection, as the tableName shouldn't be coming from the user anyway.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜