将struct映射到mysql表,并将行绑定到struct

时间:2014-03-25 02:28:34

标签: go

这是我使用go-sql-driver的第一个脚本。

我的mysql表(PRODUCT)如下所示:

id int
name varchar(255)
IsMatch tinyint(1)
created datetime

我想简单地从表中加载一行,并将其绑定到结构。

到目前为止,我有这个:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

type Product struct {
    Id    int64
  Name  string
  IsMatch ??????????
  Created ?????
}

func main() {
    fmt.Printf("hello, world!\n")

    db, err := sql.Open("mysql", "root:@/product_development")
    defer db.Close()

    err = db.Ping()
    if err != nil {
        panic(err.Error()) // proper error handling instead of panic in your app
    }

    rows, err := db.Query("SELECT * FROM products where id=1")
    if err != nil {
        panic(err.Error()) // proper error handling instead of panic in your app
    }

}

现在我需要:

1. What datatype in Go do I use for tinyint and datetime?
2. How to I map the rows to a Product struct?

2 个答案:

答案 0 :(得分:5)

我在Go中使用哪种数据类型用于tinyint和datetime?

有关database/sql包将使用的类型的提示,请查看database/sql.Scanner的文档,其中列出了database / sql本身使用的Go类型:

int64
float64
bool
[]byte
string
time.Time
nil - for NULL values

这会让您尝试int64的{​​{1}}和IsMatch的{​​{1}}。我相信在现实中你可以使用几乎任何大小的time.Time(甚至Created,你必须检查来源)int,因为它可以存储&#34 ;不会损失精确度。" go-mysql-driver的文档说明您需要将bool添加到DSN,以便自动解析时间。时间或使用NullTime

如何将行映射到Product结构?

使用Rows.Scan,应该是非常明确的,例如:

IsMatch

这会将列扫描到结构的字段中并将它们累积到切片中。 (不要忘记关闭行!)

答案 1 :(得分:-1)

如何将行映射到Product结构? 您可以使用reflecttable rows in db绑定到struct,然后  自动匹配没有长Hard-Code sql字符串的值,这很容易出错。 这是一个简单的演示:sqlmapper