思路
结构对象映射出来:类名,成员名,成员值
package dao import ( _ "ChbeeGoTest/models" "ChbeeGoTest/utils/myLog" "fmt" "reflect" "strings" ) type Dao struct { } var DaoInter = new(Dao) //将对象映射到表格中,返回主键ID func (this *Dao) Insert(obj interface{}) { //对象转表格 table := obj2table(obj) fmt.Println(table.TbName) //序列化列名 cloums := strings.Join(table.Cloum, ",") fmt.Println(cloums) //插入语句 stmt, err := Db.Prepare(`INSERT User(UserName,PassWord,TrueName,Mail,HeadImg,LastLogin,Coin) VALUES(?,?,?,?,?,?,?)`) if err != nil { myLog.Logger.Fatal(err) } res, err := stmt.Exec(table.values...) if err != nil { fmt.Print("插入失败") myLog.Logger.Fatal(err) } id, err := res.LastInsertId() fmt.Print("插入成功,插入的ID是:", id) } type table struct { TbName string //Fild map[string]interface{} Cloum []string values []interface{} } type User struct { PlayerId int UserName string PassWord string TrueName string Mail string HeadImg string LastLogin uint64 Coin int } //对象转成表 func obj2table(obj interface{}) *table { tb := new(table) typeObj := reflect.TypeOf(obj) //表名 tb.TbName = typeObj.Elem().Name() //列 //tb.Fild = make(map[string]interface{}) tb.Cloum = make([]string, 1) tb.values = make([]interface{}, 1) for i := 0; i < typeObj.Elem().NumField(); i++ { //列名 cloumName := typeObj.Elem().Field(i).Name tb.Cloum = append(tb.Cloum, cloumName) //列值 val := reflect.ValueOf(obj).Elem().FieldByName(cloumName) tb.values = append(tb.values, val) //装入map //tb.Fild[cloumName] = val } return tb }
有疑问加站长微信联系(非本文作者)