将结构体映射到MySQL表,并将行绑定到结构体。

huangapple go评论105阅读模式
英文:

Mapping struct to mysql table, and binding row to struct

问题

这是我使用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. 在Go中,我应该使用什么数据类型来表示tinyint和datetime?
  2. 如何将行映射到Product结构体中?
英文:

This is my first script using go-sql-driver.

My mysql table (PRODUCT) looks like:

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

I want to simply load a row from a table, and bind it to a struct.

I have this so far:

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
	}

}

Now I need to:

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

答案1

得分: 6

在Go语言中,你可以使用以下数据类型来表示tinyint和datetime:

  • 对于tinyint,你可以使用int8或bool类型。int8类型可以表示范围在-128到127之间的整数,而bool类型可以表示布尔值(true或false)。
  • 对于datetime,你可以使用time.Time类型。time.Time类型可以表示日期和时间。

在将行映射到Product结构体时,你可以使用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() { ... }

这段代码将查询结果的每一行映射到一个Product结构体,并将这些结构体累加到一个切片中。记得在使用完rows后关闭它。

希望对你有帮助!

英文:

What datatype in Go do I use for tinyint and datetime?

For a hint as to the types that the database/sql package will be using, have a look at the documentation for database/sql.Scanner, which lists the Go types used within database/sql itself:

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

This would lead you to try int64 for IsMatch and time.Time for Created. I believe in reality you can use pretty much any sized int (maybe even bool, you'd have to check the source) for IsMatch because it can be stored "without loss of precision." The documentation for go-mysql-driver explains that you will need to add parseTime=true to your DSN in order for it to parse into a time.Time automatically or use NullTime.

How to I map the rows to a Product struct?

It should be something pretty strightforward, using Rows.Scan, like:

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() { ... }

This scans the columns into the fields of a struct and accumulates them into a slice. (Don't forget to Close the rows!)

答案2

得分: -1

如何将行映射到Product结构体?
你可以使用reflect将数据库中的表行绑定到一个结构体,并自动匹配值,而不需要编写冗长的Hard-Code SQL语句,这样容易出错。
这是一个简单的示例:sqlmapper

英文:

How to I map the rows to a Product struct?
You can use reflect to bind table rows in db to a struct, and
automatically match values without long Hard-Code sql string which is easy to make mistakes.
this is a light demo: sqlmapper

huangapple
  • 本文由 发表于 2014年3月25日 10:28:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/22624386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定