为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
隔江千里 2022-08-24 11:25:12
我创建了一个在postgres数据库上执行查询的func。我使用驱动程序 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 stringmyname is a stringlastname is a string2020-12-12 is a stringemail is a stringCali is a stringCalle is a stringmypassword is a string12334455es 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 方法无法按预期解析参数
查看完整描述

1 回答

?
当年话下

TA贡献1890条经验 获得超9个赞

解决后,对于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)


查看完整回答
反对 回复 2022-08-24
  • 1 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号