【问题标题】:Posting Column name as Integer将列名称发布为整数
【发布时间】:2012-01-17 07:50:18
【问题描述】:

我有 gameid、hometeamid、visitorteamid、winnerid 都为 int。

查询

Update game set winnerid=hometeamid where gameid=1; 

在 Mysql 工作台上运行良好。

我试图从准备好的语句中运行相同的语句,但没有成功抛出错误

java.sql.BatchUpdateException: Incorrect integer value: 'hometeamid' for column 'winnerId' at row 1

因为“hometeamid”是作为字符串传递的。 代码如下

String query = "update `match` set winnerid= ? where  gameid=?";
Map<Integer, String> data = getMap();//gameid and either 'hometeamid' or 'awaytemid'
try {
    PreparedStatement ps = connection.prepareStatement(query);
for (Map.Entry<Integer, String> entry : data.entrySet()) {
    ps.setObject(1, entry.getValue());
    ps.setInt(2, entry.getKey());
    ps.addBatch();
}
ps.executeBatch();
} catch (SQLException e) {
        logger.error(e, e);
} finally {
    closeQuietly(connection);
}

如何从 PreparedStatement 正确运行更新?

非常感谢任何其他改进建议。

【问题讨论】:

  • entry.getValue() 可能返回"hometeamid" (string),它不是整数。
  • 是的,但我需要它作为不带引号的字符串,因为它是列名。

标签: java mysql jdbc prepared-statement


【解决方案1】:

将您的查询更改为:

String query = "update `match` set winnerid = case when ? = 'hometeamid' then hometeamid else visitorteamid end where  gameid=?"

【讨论】:

    【解决方案2】:

    您不能在准备好的语句中将列名作为参数传递。您只能传递值。

    如果你真的需要这个列名是动态的,那么你必须使用字符串连接来构建这部分查询。

    【讨论】:

    • ION 正在使用您的 guava 重试器并喜欢它。
    猜你喜欢
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    相关资源
    最近更新 更多