mysql - 在 Groovy SQL 中使用参数的正确方法

标签 mysql json groovy

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

当我运行下面的代码时,我收到有关 SQL 注入(inject)的警告,我收到的警告如下。

In Groovy SQL please do not use quotes around dynamic expressions (which start with $) as this means we cannot use a JDBC PreparedStatement and so is a security hole. Groovy has worked around your mistake but the security hole is still there.

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

Sql failed to process query unterminated ' character

@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()
}

但我收到错误

Detail: Expected JSON value, but found ":". Position: 167

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

最佳答案

绑定(bind)名称周围不得有引号。

使用 :json 而不是 ':json'

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

关于mysql - 在 Groovy SQL 中使用参数的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42410469/

相关文章:

php - 通过 PHP 使用 MySQL 数据库表中的值生成 SVG 图形

mysql - 在没有 ORDER BY 的情况下使用 LIMIT 是否安全

php - 查询构建器对象在以前构建的对象中看不到别名 (Laravel)

javascript - 未捕获的语法错误 : Unexpected token : for a valid JSON

json - json 对象的 Handlebars 数组

elasticsearch - 用Elasticsearch进行Groovy编程

php - MySQL Inner Join 涉及三个表

javascript - 显示 JSON 数据中的图像?

grails - Grails中的访问关系表

grails - Groovy PageRenderer无法呈现GSP