dtfbj24048 2019-09-15 11:55
浏览 111

sql:预期0参数,得到2

I'm struggling to properly utilize sqlx and the pq driver for Postgres to create a row in the database. Let's start simple:

I have a user, role and user_role table. I want to insert a role into the database and get the ID of the inserted row. This works flawlessly using the following sql:

const createRoleSQL = "INSERT INTO role (name) VALUES (:name) RETURNING id"

To make that work in go, I prepare the statement at some point:

createStmt, err := db.PrepareNamed(createRoleSQL)
if err != nil {
    // ...
}

When creating, I run the query as part of a transaction tx. role is obviously a struct with the correct fields and db tags:

if err := tx.NamedStmt(createStmt).QueryRow(role).Scan(&role.ID); err != nil {
    // ...
}

This works perfectly fine.

Now I wanted to extend that and insert a new role and assign it to a user:

const createUserRoleSQL = `
DO $$
DECLARE role_id role.id%TYPE;
BEGIN
    INSERT INTO role (name) VALUES ($2) RETURNING id INTO role_id;
    INSERT INTO user_role (user_id, role_id) VALUES ($1, role_id);
END $$`

createStmt, err := db.Preparex(createUserRoleSQL)
if err != nil {
    // ...
}

if err := tx.Stmtx(createStmt).QueryRow(userID, role.Name).Scan(&role.ID); err != nil {
    // ...
}

Unfortunately this fails with sql: expected 0 arguments, got 2. Is it possible to achieve what I want to do, with a single query?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 mmocr的训练错误,结果全为0
    • ¥15 python的qt5界面
    • ¥15 无线电能传输系统MATLAB仿真问题
    • ¥50 如何用脚本实现输入法的热键设置
    • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
    • ¥30 深度学习,前后端连接
    • ¥15 孟德尔随机化结果不一致
    • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
    • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
    • ¥15 谁有desed数据集呀