dongsaolian8786 2017-09-06 21:10
浏览 87
已采纳

如何使用golang sql在postgres中选择整个表格?

I'm fairly new to posgres and Go, but have been struggling for a while on this. I'm currently trying to send a query to retrieve everything from a table. When I try to use

SELECT * FROM land_registry_price_paid_uk

within postgres, it shows everything, but when I do the same using Query, I get.

sql: expected 16  destination arguments in Scan, not 1

This is the current code that I have.

fmt.Printf("user: %s, password: %s, dbName: %s", user, password, dbName)
connectionString := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=%s", user, password, dbName, "disable")
var err error
a.DB, err = sql.Open("postgres", connectionString)
if err != nil {
    log.Fatal(err)
}
rows, err := a.DB.Query("SELECT ( * ) FROM land_registry_price_paid_uk")
if err != nil {
    log.Fatal(err)
}
defer rows.Close()
println(rows)
for rows.Next() {
    var name string
    if err := rows.Scan(&name); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("this is something: %s
", name)

Any help is appreciated.

  • 写回答

2条回答 默认 最新

  • duannai5879 2017-09-06 21:25
    关注

    Looks like your query is working just fine, you are returning 16 columns of data and trying to scan them all into a single string variable, you will need to provide a holder variable for each column:

    var name string
    // vars to hold other column values go here
    
    // then reference vars in table order as args to row.Scan below
    if err := rows.Scan(&name); err != nil {
        log.Fatal(err)
    }
    

    if you have not used sql/go before you may also want to look into the special types provided for coping with nullable values as you will likely need these as well:

    NullString example

    Update:

    To further illustrate, say you had a three column table which consisted of the following fields:

    • id (int)
    • name (string)
    • optional_data (string, nullable)

    You might read the row as follows (not tested):

    var (
        id int 
        name string
        optionalData sql.NullString
    )
    
    if err := rows.Scan(&id, &name, &optionalData); err != nil {
        log.Fatal(err)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 求直线方程 使平面上n个点在直线同侧并且距离总和最小
  • ¥50 java算法,给定试题的难度数量(简单,普通,困难),和试题类型数量(单选,多选,判断),以及题库中各种类型的题有多少道,求能否随机抽题。
  • ¥50 rk3588板端推理
  • ¥250 opencv怎么去掉 数字0中间的斜杠。
  • ¥15 这种情况的伯德图和奈奎斯特曲线怎么分析?
  • ¥250 paddleocr带斜线的0很容易识别成9
  • ¥15 电子档案元素采集(tiff及PDF扫描图片)
  • ¥15 flink-sql-connector-rabbitmq使用
  • ¥15 zynq7015,PCIE读写延时偏大
  • ¥15 使用spss做psm(倾向性评分匹配)遇到问题