dousonghs58612 2015-10-16 13:24
浏览 282
已采纳

生成错误“ rows.Columns未定义(类型* sql.Row没有字段或方法列)”

I want to print multiple rows having multiple columns from my postgresql database using golang.while buildng the following code

package main

import (
    "database/sql"
    "fmt"
    "github.com/gin-gonic/gin"
    _ "github.com/lib/pq"
    "log"
    "runtime"
)

func main() {

    runtime.GOMAXPROCS(runtime.NumCPU())

    db, err := sql.Open("postgres", "dbname=sample_data user=postgres password=postgres sslmode=disable")
    defer db.Close()
    if err != nil {
        fmt.Println("error connecting to DB")
    }
    r := gin.Default()
    r.GET("/cin_display", func(c *gin.Context) {
        rows := db.QueryRow("SELECT cin FROM companies limit 1;")

        columns, _ := rows.Columns()
        count := len(columns)
        values := make([]interface{}, count)
        valuePtrs := make([]interface{}, count)

        for rows.Next() {

            for i, _ := range columns {
                valuePtrs[i] = &values[i]
            }

            rows.Scan(valuePtrs...)

            for i, col := range columns {

                var v interface{}

                val := values[i]

                b, ok := val.([]byte)

                if ok {
                    v = string(b)
                } else {
                    v = val
                }

                fmt.Println(col, v)
            }
        }

    })
}

func Connect(connectionString string) *sql.DB {
    db, err := sql.Open("postgres", connectionString)
    if err != nil {
        log.Fatal(err)
    }
    return db
}

I am getting the errors like

rows.Columns undefined (type *sql.Row has no field or method Columns)

rows.Next undefined (type *sql.Row has no field or method Next)

how to solve this?

  • 写回答

2条回答 默认 最新

  • drux41001 2015-10-16 13:28
    关注

    QueryRow returns a single *sql.Row

    What you want is Query, which will give you *sql.Rows which has the methods you are trying to use.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据