【问题标题】:Correct way to use parameters within Groovy SQL在 Groovy SQL 中使用参数的正确方法
【发布时间】:2017-02-23 08:25:33
【问题描述】:

我正在使用 Groovy SQL 执行一个查询,该查询将一些 JSON 添加到我的 Postgres JSONB 数据库中的一个数组中。

当我运行下面的代码时,我收到一个关于 SQL 注入的警告,我收到的警告如下。

在 Groovy SQL 中,请不要在动态表达式周围使用引号 (以 $ 开头),因为这意味着我们不能使用 JDBC PreparedStatement 等是一个安全漏洞。 Groovy 已经解决了 你的错误,但安全漏洞仍然存在。

如果我的 JSON 中有 ' 字符,我也无法将 JSON 保存在我的数据库中,我收到以下错误:

Sql 未能处理查询未终止的'字符

@Override
Operation save(Player player) {
    String json = objectMapper.writeValueAsString(player)
    Blocking.get {
        sql.executeUpdate("""
            UPDATE site_content
            SET content = jsonb_set(content, '{playersContainer,players}'::text[], content->'playersContainer'->'players' || '${json}'::jsonb)
            where id = :id
            """,id: player.teamId)
    }.operation()
}

我已经把代码改成了这个

@Override
Operation save(Player player) {
    String json = objectMapper.writeValueAsString(player)
    Blocking.get {
        sql.executeUpdate("""
            UPDATE site_content
            SET content = jsonb_set(content, '{playersContainer,players}'::text[], content->'playersContainer'->'players' || ':json'::jsonb)
            where id = :id
            """, json: json, id: player.teamId)
    }.operation()
}

但我得到了错误

详细信息:预期的 JSON 值,但找到了“:”。位置:167

将动态参数放入我的 Groovy SQL 查询的正确方法是什么?当我将它发送到查询时,我是否必须对 JSON 进行编码?在我从我的 React 应用程序发送它之前的那一刻,我做 JSON.stringfy(json) 这还不够吗?

【问题讨论】:

    标签: mysql json groovy


    【解决方案1】:

    绑定名称不能用引号引起来。

    使用:json 代替':json'

    第一个是绑定,第二个是一个以冒号开头的字符串。所以错误信息很简单:无法从字符串':json'解析json对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      相关资源
      最近更新 更多