导包
import (
"github.com/astaxie/beego/orm"
"time"
_ "github.com/lib/pq"
)
结构体
type User struct {
Id int64 `field:"id"`
Username string `field:"username"`
Password string `field:"password"`
Mobile string `field:"mobile"`
Email string `field:"email"`
EmailActive int `field:"email_active"`
Status int `field:"status"`
CreateBy int64 `field:"create_by"`
CreateTime time.Time `field:"create_time"`
UpdateBy int64 `field:"update_by"`
UpdateTime time.Time `field:"update_time"`
}
初始化
func init() {
// PostgreSQL 配置
orm.RegisterDriver("postgres", orm.DRPostgres) // 注册驱动
orm.RegisterDataBase("default", "postgres", "user=postgres password=123456 dbname=dbnamehost=127.0.0.1 port=5432 sslmode=disable")
orm.Debug = true
orm.RegisterModel(new(User))
}
QueryRow: 查询单条数据
func GetUserById(uid int64) (u *User, err error) {
o := orm.NewOrm()
u = &User{}
_ = o.Raw("select * from t_user where id = ?", uid).QueryRow(u)
return u, nil
}
QueryRows:返回数组,查询多条数据
func GetAllUsers() []*User {
o := orm.NewOrm()
var users []*User
num, err := o.Raw("select * from t_user where status = 1").QueryRows(&users)
if err != nil {
fmt.Println("user nums:", num)
}
return users
}