我想使用golang从postgresql数据库中打印多行具有多列的行。同时构建以下代码
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
}
我收到的错误如
rows.Columns undefined(类型* sql.Row没有字段或方法列)
rows.Next undefined(type * sql.Row没有字段或方法Next)
如何解决这个问题?