dousonghs58612
2015-10-16 13:24
浏览 190

生成错误“ 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.

    点赞 打赏 评论
  • douaoj0994 2018-06-27 03:43

    you masked the database/sql package here: sql := `select * from table sql is then a string, not the package. Rename the string e.g. to query and it will work

    点赞 打赏 评论

相关推荐 更多相似问题