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
}