最近在学习Go语言reflect的API,一直不得其门而入,想通过实现一个有实用价值的demo,来达到学习的目的,学以致用。
目标:使用reflect将一个结构体数据,根据对应规则,insert到mysql的对应表中。
表结构如下:
CREATE TABLE `testdata` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`nums` int(11) NOT NULL,
`money` decimal(14,2) NOT NULL,
`is_wxapp` tinyint(4) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Go语言的结构体定义如下:
type TestData struct {
name string
nums int
money float64
is_wxapp bool
}
实现一个insert函数,将Go的结构体数据实例插入数据库,使用示例如下:
func main() {
driver := "root:1234@tcp(localhost:3306)/testdb?charset=utf8"
localdb, err := sql.Open("mysql", driver)
if err != nil {
fmt.Println("connect db:", err)
return
}
testdata := &TestData{name: "test", nums: 2, money: 128.88, is_wxapp: false}
err = insert(localdb, testdata) //insert 结构体数据到数据库表中
if

本文介绍了如何使用Go语言的反射库reflect,实现将结构体数据根据特定规则插入到MySQL数据库表中。通过示例展示了结构体定义、插入函数的实现以及成功插入数据的效果。

961

被折叠的 条评论
为什么被折叠?



