简体   繁体   English

Postgres无法确定Golang应用程序中参数$ 1的数据类型

[英]Postgres could not determine data type of parameter $1 in Golang application

I am creating an application in Golang that uses Postgres using the pq driver. 我在Golang中使用pq驱动程序创建了一个使用Postgres的应用程序。 I want to make a function that can select a user-determined field from my database, but I get an error: 我想创建一个可以从我的数据库中选择用户确定的字段的函数,但是我收到一个错误:

pq: could not determine data type of parameter $1 pq:无法确定参数$ 1的数据类型

Below is the code that generated this error: 以下是生成此错误的代码:

var ifc interface{}

if err := conn.QueryRow("SELECT $1 FROM "+db+" WHERE uuid=$3 OR uri=$4 LIMIT 1", field, UUIDOrURI, UUIDOrURI).Scan(&ifc); err != nil {
    if err == sql.ErrNoRows {
        return http.StatusNotFound
    }

    log.Println(err)

    return http.StatusInternalServerError
}

Why can I not insert the field that I want to SELECT using $1 ? 为什么我不能使用$1插入我想要SELECT的字段? Is there another way to do this? 还有另一种方法吗?

You cannot use placeholders for field names. 您不能使用占位符作为字段名称。 You'll have to build the query directly, as in: 您必须直接构建查询,如下所示:

"SELECT `" + field + "` FROM "

To avoid SQL injections, make sure that the field is part of a list of allowed fields beforehand. 要避免SQL注入,请确保该字段事先是允许字段列表的一部分。

IMHO an easier way, but not safe, to create SQL queries is to use fmt.Sprintf: 恕我直言,创建SQL查询更简单但不安全的方法是使用fmt.Sprintf:

query := fmt.Sprintf("SELECT %s FROM %s WHERE uuid=%s", field, db, UUIDOrURI)
if err := conn.QueryRow(query).scan(&ifc); err != nil {

}

You can even specify an argument index: 您甚至可以指定参数索引:

query := fmt.Sprintf("SELECT %[2]s FROM %[1]s", db, field)

In order to ease the development, I recommend to use a package for the postgresql communication, I tried this one and worked great. 为了便于开发,我建议使用一个包进行postgresql通信,我试过这个并且效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM