通过反射插入数据
平常往数据库中插入数据的时候,我们总是先拿到需要的column和value,然后拼接SQL语句,有了反射后,我们只要通过结构体就可以拿到其所有的column和value,然后拼接就好了,一个函数适用于所有的场景
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"reflect"
"strings"
)
type Data struct {
ID string `json:"id"`
Name string `json:"name"`
Addr string `json:"addr"`
}
type Location struct {
X int `json:"x"`
Y int `json:"y"`
ZIndex int `json:"zIndex"`
Status int `json:"status"`
ParentID int `json:"parentId"`
}
var db *sqlx.DB
var err error
func main() {
dsn := "root:123456@tcp(127.0.0.1:3306)/music_world?charset=utf8&parseTime=True"
//dsn := "root:123456@tcp(127.0.0.1:3306)/music_world?charset=utf8&parseTime=True"
db, err = sqlx.Connect("mysql", dsn)
if err != nil {
fmt.Printf("打开数据库错误:%v\n", err)
return
}
data := Data{
ID: "id1",
Name: "small",
Addr: "kexing1",
}
fmt.Println(data.BuildSql())
loc := Location{
X: 11,
Y: 22,
ZIndex: 33,
Status: 44,
ParentID: 55,
}
sql:=loc.BuildSql()
fmt.Println(sql)
insert(sql)
}
func insert(sql string) {
res, err := db.Exec(sql)
if err != nil {
panic(err)
}
fmt.Println(res.RowsAffected())
}
// BuildSqlINSERT INTO `music_world`.`t_mworld_defaultprops` (`id`, `x`, `y`, `zIndex`, `status`, `parentId`) VALUES ('2', '2', '2', '2', '2', '2');
func (obj *Location) BuildSql() string {
columns := strings.Builder{}
values := strings.Builder{}
typ := reflect.TypeOf(obj).Elem()
value := reflect.ValueOf(obj).Elem()
for i := 0; i < typ.NumField(); i++ {
k := typ.Field(i).Tag.Get("json")
v := value.Field(i)
if columns.Len() != 0 {
columns.WriteString(",")
values.WriteString(",")
}
columns.WriteString(fmt.Sprintf("`%v`", k))
values.WriteString(fmt.Sprintf("'%v'", v))
//columns.WriteString("=")
//columns.WriteString(fmt.Sprintf("%v", v))
}
sql := fmt.Sprintf("insert into t_mworld_defaultprops(%s) values(%s)", columns.String(), values.String())
return sql
}
// BuildSql INSERT INTO `music_world`.`t_mworld_defaultprops` (`id`, `x`, `y`, `zIndex`, `status`, `parentId`) VALUES ('2', '2', '2', '2', '2', '2');
func (obj *Data) BuildSql() string {
columns := strings.Builder{}
values := strings.Builder{}
typ := reflect.TypeOf(obj).Elem()
value := reflect.ValueOf(obj).Elem()
for i := 0; i < typ.NumField(); i++ {
k := typ.Field(i).Tag.Get("json")
v := value.Field(i)
if columns.Len() != 0 {
columns.WriteString(",")
values.WriteString(",")
}
columns.WriteString(fmt.Sprintf("`%s`", k))
values.WriteString(fmt.Sprintf("'%s'", v))
//columns.WriteString("=")
//columns.WriteString(fmt.Sprintf("%v", v))
}
sql := fmt.Sprintf("insert into t_crud(%s) values(%s)", columns.String(), values.String())
return sql
}
网友评论