当前位置: 首页 > 工具软件 > QueryBuilder > 使用案例 >

golang :ORM之 QueryBuilder

上官飞
2023-12-01

使用ORM的时候我们可以采用QueryBuilder 去构造SQL
qb的接口

// QueryBuilder is the Query builder interface
type QueryBuilder interface {
	Select(fields ...string) QueryBuilder
	ForUpdate() QueryBuilder
	From(tables ...string) QueryBuilder
	InnerJoin(table string) QueryBuilder
	LeftJoin(table string) QueryBuilder
	RightJoin(table string) QueryBuilder
	On(cond string) QueryBuilder
	Where(cond string) QueryBuilder
	And(cond string) QueryBuilder
	Or(cond string) QueryBuilder
	In(vals ...string) QueryBuilder
	OrderBy(fields ...string) QueryBuilder
	Asc() QueryBuilder
	Desc() QueryBuilder
	Limit(limit int) QueryBuilder
	Offset(offset int) QueryBuilder
	GroupBy(fields ...string) QueryBuilder
	Having(cond string) QueryBuilder
	Update(tables ...string) QueryBuilder
	Set(kv ...string) QueryBuilder
	Delete(tables ...string) QueryBuilder
	InsertInto(table string, fields ...string) QueryBuilder
	Values(vals ...string) QueryBuilder
	Subquery(sub string, alias string) string
	String() string
}

通过上面的接口我们可以看到 QueryBuilder 返回值也是一个QueryBuilder ,所以我们可以像平时写SQL构建自己的SQL解析语句

	orm.RegisterDataBase("default", "mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8", 30)
	orm.RegisterModel(new(UserInfo))
	o := orm.NewOrm()

上面代码 ,链接了数据库,创建了RegisterModel ,创建了Orm对象
接着创建QueryBuilder

qb, _ := orm.NewQueryBuilder("mysql")

目前支持以下四种数据库初始化

// NewQueryBuilder return the QueryBuilder
func NewQueryBuilder(driver string) (qb QueryBuilder, err error) {
	if driver == "mysql" {
		qb = new(MySQLQueryBuilder)
	} else if driver == "tidb" {
		qb = new(TiDBQueryBuilder)
	} else if driver == "postgres" {
		err = errors.New("postgres query builder is not supported yet")
	} else if driver == "sqlite" {
		err = errors.New("sqlite query builder is not supported yet")
	} else {
		err = errors.New("unknown driver for query builder")
	}
	return
}

构造sql语句

qb.Select("*").From("user_info")
sql := qb.String()

执行sql

o.Raw(sql).QueryRows(&user)
 类似资料: