【问题标题】:How correctly pass arguments to the SQL request via the sqlx package in Golang?如何通过 Golang 中的 sqlx 包正确地将参数传递给 SQL 请求?
【发布时间】:2021-04-07 08:23:58
【问题描述】:

在我的 Golang (1.15) 应用程序中,我使用 sqlx 包来处理 PostgreSQL 数据库 (PostgreSQL 12.5)。

当我尝试使用参数 PostgreSQL 数据库执行 SQL 语句时,它会引发错误:

错误:无法确定参数 $1 的数据类型(SQLSTATE 42P18): PgError null

根据official documentation,这个错误意味着传递了INDETERMINATE DATATYPE

organizationId 有价值。它不是 null/nil 或空的。另外,它的数据类型是一个简单的内置数据类型*string

带有查询方法的代码 sn-p

rows, err := cr.db.Query(`
    select
        channels.channel_id::text,
        channels.channel_name::text
    from
        channels
    left join organizations on
        channels.organization_id = organizations.organization_id
    where
        organizations.tree_organization_id like concat( '%', '\', $1, '%' );`, *organizationId)

if err != nil {
    fmt.Println(err)
}

我也尝试使用NamedQuery,但它也会引发错误:

错误:“:”处或附近的语法错误(SQLSTATE 42601):PgError null

使用 NamedQuery 方法编写代码 sn-p

args := map[string]interface{}{"organization_id": *organizationId}

rows, err := cr.db.NamedQuery(`
    select
        channels.channel_id::text,
        channels.channel_name::text
    from
        channels
    left join organizations on
        channels.organization_id = organizations.organization_id
    where
        organizations.tree_organization_id like concat( '%', '\', :organization_id, '%' );`, args)

if err != nil {
    fmt.Println(err)
}

很可能,参数没有正确传递给我的请求。有人可以解释如何解决这种奇怪的行为吗?

P.S. 我必须马上说,我不想通过concatenationfmt.Sprintf 方法形成一个sql 查询。不安全。

【问题讨论】:

  • PostgreSQL 无法推断 $1 的类型。试试这个: concat( '%', '\', $1::text, '%' )

标签: sql postgresql go


【解决方案1】:

嗯,我找到了解决这个问题的方法。

我在 sqlx 包的 github 存储库中找到了discussion

第一个选项中,我们可以在查询之外连接我们的搜索字符串。这应该仍然可以免受注入攻击。

第二选择试试这个:concat( '%', '\', $1::text, '%' )。正如 Bjarni Ragnarsson 在评论中所说,PostgreSQL 无法推断出$1 的类型。

【讨论】:

    猜你喜欢
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 2016-04-03
    • 2021-06-29
    • 2014-04-02
    相关资源
    最近更新 更多