一尘不染

sql:扫描列数未知的行(从*中选择*)

go

我有一个t包含很多列的表,而我的sql是这样的:select * from t。现在,我只想从返回的宽行集中扫描一两列。但是,sql.Scan接受dest ...interface{}作为参数。这是否意味着我必须扫描所有内容并仅使用所需的列?

我知道我可以将sql从更改select *select my_favorite_rows,但是在这种情况下,我无法更改sql。


阅读 248

收藏
2020-07-02

共1个答案

一尘不染

您可以使用Rows.Columns,例如

package main

import (
    "database/sql"
    "fmt"

    "github.com/lib/pq"
)

type Vehicle struct {
    Id     int
    Name   string
    Wheels int
}

// VehicleCol returns a reference for a column of a Vehicle
func VehicleCol(colname string, vh *Vehicle) interface{} {
    switch colname {
    case "id":
        return &vh.Id
    case "name":
        return &vh.Name
    case "wheels":
        return &vh.Wheels
    default:
        panic("unknown column " + colname)
    }
}

func panicOnErr(err error) {
    if err != nil {
        panic(err.Error())
    }
}

func main() {
    conn, err := pq.ParseURL(`postgres://docker:docker@172.17.0.2:5432/pgsqltest?schema=public`)
    panicOnErr(err)

    var db *sql.DB
    db, err = sql.Open("postgres", conn)
    panicOnErr(err)

    var rows *sql.Rows
    rows, err = db.Query("select * from vehicle")
    panicOnErr(err)

    // get the column names from the query
    var columns []string
    columns, err = rows.Columns()
    panicOnErr(err)

    colNum := len(columns)

    all := []Vehicle{}

    for rows.Next() {
        vh := Vehicle{}

        // make references for the cols with the aid of VehicleCol
        cols := make([]interface{}, colNum)
        for i := 0; i < colNum; i++ {
            cols[i] = VehicleCol(columns[i], &vh)
        }

        err = rows.Scan(cols...)
        panicOnErr(err)

        all = append(all, vh)
    }

    fmt.Printf("%#v\n", all)
}
2020-07-02