微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 postgres 驱动程序在 golang 中使用参数执行查询时出错

如何解决使用 postgres 驱动程序在 golang 中使用参数执行查询时出错

我创建了一个在 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,cellphone) VALUES ('f1571b24-d88e-42b3-907e-13f46efabacc is','myname','lastname','2020-12-12','email','Cali','Calle','mypassword','12334455es')

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

解决方法

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

所以正确的查询是

help

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。