golang处理grose返回来的数据

step1:下载需要的包

 go get github.com/gohouse/gorose
 go get github.com/astaxie/beego
 go get github.com/go-sql-driver/mysql
 go get github.com/gohouse/utils

//step2:定义一个表结构相对应的结构体

type User struct {
	Id int64 `orm:"id"`
	Account string `orm:"account"`
	Password string `orm:"password"`
	Ip string    `orm:"ip"`
	Create_time int64 `orm:"create_time"`
	Update_time int64 `orm:"update_time"`

}

数据库配置

var DbConfig = &gorose.DbConfigSingle {
	Driver:          "mysql", // 驱动: mysql/sqlite/oracle/mssql/postgres
	EnableQueryLog:  false,   // 是否开启sql日志
	SetMaxOpenConns: 0,    // (连接池)最大打开的连接数,默认值为0表示不限制
	SetMaxIdleConns: 0,    // (连接池)闲置的连接数
	Prefix:          "", // 表前缀
	Dsn:             "root:root@tcp(localhost:3306)/beego?charset=utf8", // 数据库链接
}

//查询数据库,返回值类型为定义的strutct类型
**

func FindUser(username string) ( result []User){
	var user []User
	db, err := gorose.Open(dbConfig)
	if err!=nil {
		log.Fatal(err)
		fmt.Println(err)
		return
	}
    data,_:=db.Table("user").Where("account="+username).Limit(1).Get()
	tmp:=utils.JsonEncode(data)
	err=json.Unmarshal([]byte(tmp),&user)
	if err!=nil{
		fmt.Println(err)
	}
	result=user
	db.Close()
	return
}

特别说明:
data,_:=db.Table(“user”).Where(“account=”+username).Limit(1).Get()
这句代码data变量返回来的是[]map[string]interface{},
tmp:=utils.JsonEncode(data)
这句代码返回是将返回来的对象转换为json字符串
err=json.Unmarshal([]byte(tmp),&user)
这句代码将json字符串中的数据解析为自定义的struct类型

方式二:直接返回map

  func FindUser(username string) ( result []map[string]interface{}){
    	db, err := gorose.Open(dbConfig)
    	if err!=nil {
    		log.Fatal(err)
    		return
    	}
        data,_:=db.Table("user").Where("account="+username).Limit(1).Get()
    	result=data
    	db.Close()
    	return
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值