基于go的反射实现查询生成器

基于go的反射实现查询生成器

参考go系列教材反射章节,源代码没有实现输出字段,我根据对反射的理解实现了对字段进行输出。beego的orm就是基于反射实现的。

/*
# @Time : 2019-01-05 16:57
# @Author : smallForest
# @SoftWare : GoLand
*/
package main

import (
    "fmt"
    "reflect"
)

type order3 struct {
    ordId      int
    customerId int
}
type employee3 struct {
    name    string
    id      int
    address string
    salary  int
    country string
}

func createQuery3(q interface{}) {
    if reflect.ValueOf(q).Kind() == reflect.Struct {
        t := reflect.TypeOf(q).Name()

        query := fmt.Sprintf("insert into %s(", t)
        Names := reflect.TypeOf(q)
        for j := 0; j < Names.NumField(); j++ {
            if j==0{
                query = fmt.Sprintf("%s%s",query,Names.Field(j).Name)
            }else{
                query = fmt.Sprintf("%s,%s",query,Names.Field(j).Name)
            }
        }
        query = fmt.Sprintf("%s) values(",query)

        v := reflect.ValueOf(q)
        for i := 0; i < v.NumField(); i++ {
            switch v.Field(i).Kind() {
            case reflect.Int:
                if i == 0 {
                    query = fmt.Sprintf("%s%d", query, v.Field(i).Int())
                } else {
                    query = fmt.Sprintf("%s,%d", query, v.Field(i).Int())
                }
            case reflect.String:
                if i == 0 {
                    query = fmt.Sprintf("%s\"%s\"", query, v.Field(i).String())

                } else {
                    query = fmt.Sprintf("%s,\"%s\"", query, v.Field(i).String())
                }
            default:
                fmt.Println("Unsupported type")
                return

            }
        }
        query = fmt.Sprintf("%s)", query)
        fmt.Println(query)
        return
    }
    fmt.Println("unsupported type")
}

func main() {
    o := order3{456, 33}
    createQuery3(o)
    e3 := employee3{
        "Naveen",
        555,
        "Coimbatore",
        9000,
        "India",
    }
    createQuery3(e3)
    i := 90
    createQuery3(i)
}
    原文作者:SmallForest
    原文地址: https://segmentfault.com/a/1190000017787628
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞