登录
首页 >  Golang >  Go问答

在 golang 中使用 postgres 驱动程序查询时,执行带参数的查询出现错误

来源:stackoverflow

时间:2024-02-13 20:24:23 439浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《在 golang 中使用 postgres 驱动程序查询时,执行带参数的查询出现错误》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我创建了一个在 postgres 数据库上执行查询的函数。我使用驱动程序github.com/lib/pq

但是如果我运行这个:

_, err := repository.db.execcontext(ctx, query, args...)

查询在哪里

insert into fakeclients (uuid, name, last_name, birth_day, email, city, address, password, cellphone) values (?, ?, ?, ?, ?, ?, ?, ?, ?)

args 是一个包含该值及其类型的切片

f1571b24-d88e-42b3-907e-13f46efabacc is a string
myname is a string
lastname is a string
2020-12-12 is a string
email is a string
cali is a string
calle is a string
mypassword is a string
12334455es is a string

该表是使用此属性创建的

create table if not exists fakeclients (
    id                text,
    corporate_account boolean,
    name              text,
    last_name         text,
    cellphone         text,
    birth_day         text,
    email             text,
    password          text,
    city              text,
    address           text,
    primary key (id)
);

执行该查询的结果是

pq: syntax error at or near ","

但是如果我像这样插入包含查询字符串中所有值的查询,它就会起作用

INSERT INTO fakeclients (uuid, name, last_name, birth_day, email, city, address, password, cellphone) VALUES ('f1571b24-d88e-42b3-907e-13f46efabacc is', 'myname', 'lastname', '2020-12-12', 'email', 'Cali', 'Calle', 'mypassword', '12334455es')

看起来 execcontext 方法没有按预期解析参数


正确答案


已解决,对于 postgres,插值查询的正确使用是 $1、$2、$3...

所以正确的查询是

INSERT INTO fakeclients (uuid, name, last_name, birth_day, email, city, address, password, cellphone) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)

以上就是《在 golang 中使用 postgres 驱动程序查询时,执行带参数的查询出现错误》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>