go-反射机制

思路  

结构对象映射出来:类名,成员名,成员值



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
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值