在Golang中从数据库行创建Map

1hdlvixo  于 2023-05-27  发布在  Go
关注(0)|答案(5)|浏览(136)

基本上,在完成查询后,我想获取结果行并生成[]map[string]interface{},但我不知道如何使用API来实现这一点,因为Rows.Scan()函数需要特定数量的参数来匹配所请求的列数(可能还有类型)以正确获取数据。
同样,我想泛化这个调用,并将任何查询转换为[]map[string]interface{},其中Map包含Map到该行值的列名。
这可能非常低效,我计划稍后更改结构,以便interface{}是单个数据点的结构。
我如何使用数据库/sql包来实现这一点,或者如果需要的话,使用数据库/sql/驱动程序包?

nvbavucw

nvbavucw1#

看看使用sqlx,它可以比标准的数据库/sql库更容易地做到这一点:

places := []Place{}
err := db.Select(&places, "SELECT * FROM place ORDER BY telcode ASC")
if err != nil {
    fmt.Printf(err)
    return
}

很明显,你可以用[]map[string]interface{}替换[]Place{},但是如果你知道数据库的结构,在可能的情况下,最好使用结构体。您不需要像在interface{}上那样进行任何类型Assert。

pvabu6sv

pvabu6sv2#

我还没有使用过它,但我相信完成您所要求的(或多或少)的“常见”方法是使用gorp

vnjpjtjt

vnjpjtjt3#

您可以创建一个结构体来维护Map键到[]interface{}切片的位置。这样,您就不需要创建预定义的结构。例如:

IDOrder: 0
IsClose: 1
IsConfirm: 2
IDUser: 3

然后,您可以这样使用它:

// create a fieldbinding object.
  var fArr []string
  fb := fieldbinding.NewFieldBinding()

  if fArr, err = rs.Columns(); err != nil {
    return nil, err
  }

  fb.PutFields(fArr)

  //
  outArr := []interface{}{}

  for rs.Next() {
    if err := rs.Scan(fb.GetFieldPtrArr()...); err != nil {
      return nil, err
    }

    fmt.Printf("Row: %v, %v, %v, %s\n", fb.Get("IDOrder"), fb.Get("IsConfirm"), fb.Get("IDUser"), fb.Get("Created"))
    outArr = append(outArr, fb.GetFieldArr())
  }

输出示例:

Row: 1, 1, 1, 2016-07-15 10:39:37 +0000 UTC
Row: 2, 1, 11, 2016-07-15 10:42:04 +0000 UTC
Row: 3, 1, 10, 2016-07-15 10:46:20 +0000 UTC
SampleQuery: [{"Created":"2016-07-15T10:39:37Z","IDOrder":1,"IDUser":1,"IsClose":0,"IsConfirm":1},{"Created":"2016-07-15T10:42:04Z","IDOrder":2,"IDUser":11,"IsClose":0,"IsConfirm":1},{"Created":"2016-07-15T10:46:20Z","IDOrder":3,"IDUser":10,"IsClose":0,"IsConfirm":1}]

请参阅下面的完整示例或fieldbinding

main.go

package main

import (
    "bytes"
    "database/sql"
    "encoding/json"
    "fmt"
)

import (
    _ "github.com/go-sql-driver/mysql"
    "github.com/junhsieh/goexamples/fieldbinding/fieldbinding"
)

var (
    db *sql.DB
)

// Table definition
// CREATE TABLE `salorder` (
//   `IDOrder` int(10) unsigned NOT NULL AUTO_INCREMENT,
//   `IsClose` tinyint(4) NOT NULL,
//   `IsConfirm` tinyint(4) NOT NULL,
//   `IDUser` int(11) NOT NULL,
//   `Created` datetime NOT NULL,
//   `Changed` datetime NOT NULL,
//   PRIMARY KEY (`IDOrder`),
//   KEY `IsClose` (`IsClose`)
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

func main() {
    var err error

    // starting database server
    db, err = sql.Open("mysql", "Username:Password@tcp(Host:Port)/DBName?parseTime=true")

    if err != nil {
        panic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic
    }

    defer db.Close()

    // SampleQuery
    if v, err := SampleQuery(); err != nil {
        fmt.Printf("%s\n", err.Error())
    } else {
        var b bytes.Buffer

        if err := json.NewEncoder(&b).Encode(v); err != nil {
            fmt.Printf("SampleQuery: %v\n", err.Error())
        }

        fmt.Printf("SampleQuery: %v\n", b.String())
    }
}

func SampleQuery() ([]interface{}, error) {
    param := []interface{}{}

    param = append(param, 1)

    sql := "SELECT "
    sql += "  SalOrder.IDOrder "
    sql += ", SalOrder.IsClose "
    sql += ", SalOrder.IsConfirm "
    sql += ", SalOrder.IDUser "
    sql += ", SalOrder.Created "
    sql += "FROM SalOrder "
    sql += "WHERE "
    sql += "IsConfirm = ? "
    sql += "ORDER BY SalOrder.IDOrder ASC "

    rs, err := db.Query(sql, param...)

    if err != nil {
        return nil, err
    }

    defer rs.Close()

    // create a fieldbinding object.
    var fArr []string
    fb := fieldbinding.NewFieldBinding()

    if fArr, err = rs.Columns(); err != nil {
        return nil, err
    }

    fb.PutFields(fArr)

    //
    outArr := []interface{}{}

    for rs.Next() {
        if err := rs.Scan(fb.GetFieldPtrArr()...); err != nil {
            return nil, err
        }

        fmt.Printf("Row: %v, %v, %v, %s\n", fb.Get("IDOrder"), fb.Get("IsConfirm"), fb.Get("IDUser"), fb.Get("Created"))
        outArr = append(outArr, fb.GetFieldArr())
    }

    if err := rs.Err(); err != nil {
        return nil, err
    }

    return outArr, nil
}

字段绑定包:

package fieldbinding

import (
    "sync"
)

// NewFieldBinding ...
func NewFieldBinding() *FieldBinding {
    return &FieldBinding{}
}

// FieldBinding is deisgned for SQL rows.Scan() query.
type FieldBinding struct {
    sync.RWMutex // embedded.  see http://golang.org/ref/spec#Struct_types
    FieldArr     []interface{}
    FieldPtrArr  []interface{}
    FieldCount   int64
    MapFieldToID map[string]int64
}

func (fb *FieldBinding) put(k string, v int64) {
    fb.Lock()
    defer fb.Unlock()
    fb.MapFieldToID[k] = v
}

// Get ...
func (fb *FieldBinding) Get(k string) interface{} {
    fb.RLock()
    defer fb.RUnlock()
    // TODO: check map key exist and fb.FieldArr boundary.
    return fb.FieldArr[fb.MapFieldToID[k]]
}

// PutFields ...
func (fb *FieldBinding) PutFields(fArr []string) {
    fCount := len(fArr)
    fb.FieldArr = make([]interface{}, fCount)
    fb.FieldPtrArr = make([]interface{}, fCount)
    fb.MapFieldToID = make(map[string]int64, fCount)

    for k, v := range fArr {
        fb.FieldPtrArr[k] = &fb.FieldArr[k]
        fb.put(v, int64(k))
    }
}

// GetFieldPtrArr ...
func (fb *FieldBinding) GetFieldPtrArr() []interface{} {
    return fb.FieldPtrArr
}

// GetFieldArr ...
func (fb *FieldBinding) GetFieldArr() map[string]interface{} {
    m := make(map[string]interface{}, fb.FieldCount)

    for k, v := range fb.MapFieldToID {
        m[k] = fb.FieldArr[v]
    }

    return m
}
pgx2nnw8

pgx2nnw84#

如果你真的想要一个map,这在某些情况下是需要的,看看dbr,但是你需要使用fork(因为pr在原始repo中被拒绝了)。无论如何,分叉看起来更现代:
https://github.com/mailru/dbr
有关如何使用它的信息:
https://github.com/gocraft/dbr/issues/83

xfb7svmp

xfb7svmp5#

package main

import (
    "fmt"
    "github.com/bobby96333/goSqlHelper"
)

func main(){
    fmt.Println("hello")
    conn,err :=goSqlHelper.MysqlOpen("user:password@tcp(127.0.0.1:3306)/dbname")
    checkErr(err)
    row,err := conn.QueryRow("select * from table where col1 = ? and  col2 = ?","123","abc")
    checkErr(err)
    if *row==nil {
        fmt.Println("no found row")
    }else{
        fmt.Printf("%+v",row)
    }
}

func checkErr(err error){
    if err!=nil {
        panic(err)
    }
}

输出:

&map[col1:abc col2:123]

相关问题