duandange7480 2016-01-31 10:36
浏览 190
已采纳

恐慌:sql:扫描中应有1个目标参数,而不是<number> golang,pq,sql

I am fetching the data using db.QueryRow. Table created using Postgresql with data type jsonb. Below is code in golang

m := Message{}
err := db.QueryRow("SELECT data FROM message WHERE data->>'id'=$1", id).Scan(m.Id, m.Type, m.Title)

panic: sql: expected 1 destination arguments in Scan, not 3. As per row.Scan can pass n number of destination arguments. Whats wrong with this code?

  • 写回答

1条回答 默认 最新

  • douhan4812 2016-01-31 10:40
    关注

    The query returns one field per row. The code is scanning for three. Perhaps you want something like:

    err := db.QueryRow("SELECT data->>'id', data->>'type', data->>'title' FROM message WHERE data->>'id'=$1", id).Scan(m.Id, m.Type, m.Title)
    

    Also, pass pointers to the values:

    err := db.QueryRow("SELECT data->>'id', data->>'type', data->>'title' FROM message WHERE data->>'id'=$1", id).Scan(&m.Id, &m.Type, &m.Title)
    

    Another option is to fetch the data as a single field and decode the result with the encoding/json package.

    var p []byte
    err := db.QueryRow("SELECT data FROM message WHERE data->>'id'=$1", id).Scan(&p)
    if err != nil {
        // handle error
    }
    var m Message
    err := json.Unmarshal(p, &m)
    if err != nil {
        // handle error
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部