go - 将结构映射到 mysql 表,并将行绑定(bind)到结构

标签 go

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

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

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

我只想从表中加载一行,并将其绑定(bind)到结构。

到目前为止我有这个:

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?

最佳答案

我在 Go 中将什么数据类型用于 tinyint 和 datetime?

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

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

这会导致您尝试使用 int64 来获取 IsMatch 并使用 time.Time 来获取 Created。我相信实际上您可以为 IsMatch 使用几乎任何大小的 int(甚至可能是 bool,您必须检查源代码),因为它可以“不损失精度”地存储。 go-mysql-driver 的文档说明您需要将 parseTime=true 添加到您的 DSN,以便它自动解析为时间。时间或使用 NullTime .

如何将行映射到产品结构?

它应该是非常简单的东西,使用 Rows.Scan ,比如:

var products []*Product
for rows.Next() {
    p := new(Product)
    if err := rows.Scan(&p.ID, &p.Name, &p.IsMatch, &p.Created); err != nil { ... }
    products = append(products, p)
}
if err := rows.Err() { ... }

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

关于go - 将结构映射到 mysql 表,并将行绑定(bind)到结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22624386/

相关文章:

pointers - 在 Golang 中赋值

go - 如何在 google cloud run for firebase 中创建上下文对象

go - 动态解析文件

go - Knative pod http 请求

csv - Golang CSV 读取 : extraneous "in field error

c# - RSA SHA256 签名生成和验证

使用 Go 编程语言查找命名捕获组的正则表达式

Goroutine 在 Windows 和 Linux 上的行为不同

go - 将字符串与嵌套映射连接时无法获得适当的输出

unit-testing - 如何从无效输入测试错误条件