【问题标题】:Prepared Statement to set table nem for insert [duplicate]为插入设置表 nem 的准备好的语句 [重复]
【发布时间】:2013-04-27 18:39:19
【问题描述】:

我有一些准备好的语句在不同的表上做同样的事情:

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

有什么办法吗?

【问题讨论】:

    标签: mysql prepared-statement


    【解决方案1】:

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

    但是,您可以编写一个 Java 函数,将表或列名称作为参数并将其连接到 SQL 字符串中。不过,请注意确保对其进行清理以防止 SQL 注入攻击。

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

    【讨论】:

    • 好的,谢谢,我会重新考虑我的架构
    猜你喜欢
    • 1970-01-01
    • 2015-03-02
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    相关资源
    最近更新 更多