Prepared Statement为insert插入设置表nem

时间:2013-04-27 18:39:20

标签: mysql prepared-statement

我有一些准备好的声明,它们在不同的表上做同样的事情:

ReportImageWrongLang = con.prepareStatement("INSERT INTO userReportedWrongLang VALUES (?,?,?) ON DUPLICATE KEY UPDATE UserId=UserID");
ReportImageProhibited = con.prepareStatement("INSERT INTO userReportedImages VALUES (?,?,?) ON DUPLICATE KEY UPDATE UserId=UserID");

ReportElse = con.prepareStatement(“INSERT INTO Reportelse VALUES(?,?,?)ON DUPLICATE KEY UPDATE UserId = UserID”);

我根据java程序中的某些事件调用此语句。

我想将这个3语句改为一个语句:

Report = con.prepareStatement("INSERT INTO ? VALUES (?,?,?) ON DUPLICATE KEY UPDATE UserId=UserID");

并将第一个参数设置为表名(Report.setString(1,tableName))

但是我收到了这个错误:

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 ''userreportedimages' VALUES ('3',331,1) ON DUPLICATE KEY UPDATE UserId=UserID' at line 1

有什么办法吗?

1 个答案:

答案 0 :(得分:0)

您无法参数化SQL标识符,例如表名或列名。

但是,您可以编写一个Java函数,它将表或列名作为参数并将其连接成SQL字符串。但要小心确保它已经过清理,以防止SQL注入攻击。

也就是说,需要做这样的事情往往表明模式严重失调。具有相同结构的多个表通常可以(并且应该)组合成一个表,其中一列指示两者之间的差异。