golang sql根据struct字段来生成记录

golang sql根据struct字段来生成记录,第1张

概述/* Author : tuxpy Email : q8886888@qq.com.com Create time : 2017-11-04 23:13:08 Filename : main.go Description :*/package mainimport ( "database/sql" "errors" "fmt
/*	Author        : tuxpy	Email         : q8886888@qq.com.com	Create time   : 2017-11-04 23:13:08	filename      : main.go	Description   :*/package mainimport (	"database/sql"	"errors"	"fmt"	"reflect"	"time"	"utils"	_ "github.com/mattn/go-sqlite3")func ToStruct(rows *sql.Rows,to interface{}) error {	v := reflect.ValueOf(to)	if v.Elem().Type().Kind() != reflect.Struct {		return errors.New("Expect a struct")	}	scan_dest := []interface{}{}	column_names,_ := rows.Columns()	addr_by_column_name := map[string]interface{}{}	for i := 0; i < v.Elem().NumFIEld(); i++ {		one_value := v.Elem().FIEld(i)		column_name := v.Elem().Type().FIEld(i).Tag.Get("sql")		if column_name == "" {			column_name = one_value.Type().name()		}		addr_by_column_name[column_name] = one_value.Addr().Interface()	}	for _,column_name := range column_names {		scan_dest = append(scan_dest,addr_by_column_name[column_name])	}	return rows.Scan(scan_dest...)}func main() {	db,err := sql.Open("sqlite3","/tmp/firstlink.db")	utils.CheckerrorPanic(err)	fmt.Println(db)	db.Exec(`CREATE table userinfo (		work_ID INTEGER PRIMARY KEY autoINCREMENT,name VARCHAR(64) NulL,departname VARCHAR(64) NulL,created DATE NulL	)`)	tx,err := db.Begin()	defer func() {		tx.Commit()	}()	utils.CheckerrorPanic(err)	//	stmt,err := tx.Prepare("INSERT INTO userinfo(name,departname,created) values(?,?,?);")	//	utils.CheckerrorPanic(err)	//	//	_,err = stmt.Exec("我","爬虫","2015-12-15")	//	_,err = stmt.Exec("你","客服","2015-12-16")	//	utils.CheckerrorPanic(err)	rows,err := tx.query("SELECT work_ID,name,created FROM userinfo")	utils.CheckerrorPanic(err)	type Record struct {		name    string    `sql:"name"`		WorkID  int       `sql:"work_ID"`		Created time.Time `sql:"created"`	}	for rows.Next() {		record := Record{}		utils.CheckerrorPanic(ToStruct(rows,&record))		fmt.Println(record.WorkID,record.name,record.Created)	}}

输出:

&{0xc42000c3e0 /tmp/firstlink.db 0 {0 0} [] map[] 0 0 0xc4200ee060 false map[] map[] 0 0 0 <nil>}1 我 2015-12-15 00:00:00 +0000 UTC2 你 2015-12-16 00:00:00 +0000 UTC
总结

以上是内存溢出为你收集整理的golang sql根据struct字段生成记录全部内容,希望文章能够帮你解决golang sql根据struct字段来生成记录所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1273693.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存