Goal/QueryBuilder
LaravelLaravel

Goal 的查询构造器实现了类似 PDO 参数绑定的形式,来保护您的应用程序免受 SQL 注入攻击。因此不必清理因参数绑定而传入的字符串。查询构造器会返回你想要的 SQL 语句以及绑定参数。

安装

go get github.com/goal-web/querybuilder

运行数据库查询

根据条件从表中检索出数据

NewQuery
package querybuilder
import (
	"fmt"
)

func TestSimpleQueryBuilder() {
    query := NewQuery("users").
		Where("name", "qbhy").
        Where("age", ">", 18).
        Where("gender", "!=", 0).
        OrWhere("amount", ">=", 100).
        WhereIsNull("avatar")
	
    fmt.Println(query.ToSql())
    fmt.Println(query.GetBindings())
    // select * from users where name = ? and age > ? and gender != ? and avatar is null or amount >= ?
    // [qbhy 18 0 100]
}
SelectSql

插入语句

InsertSqlCreateSql
package querybuilder

import (
	"fmt"
	"github.com/goal-web/contracts"
)

// TestInsertSql 批量插入数据
func TestInsertSql() {
	sql, bindings := NewQuery("users").InsertSql([]contracts.Fields{
		{"name": "qbhy", "age": 18, "money": 100000000000},
		{"name": "goal", "age": 18, "money": 10},
	})
	fmt.Println(sql)
	fmt.Println(bindings)
	// insert into users (name,age,money) values (?,?,?),(?,?,?)
	// [qbhy 18 100000000000 goal 18 10]
}
// TestCreateSql 插入单个数据
func TestCreateSql() {
	sql, bindings := NewQuery("users").CreateSql(contracts.Fields{
		"name": "qbhy", "age": 18, "money": 100000000000,
	})
	fmt.Println(sql)
	fmt.Println(bindings) 
	// insert into users (name,age,money) values (?,?,?) 
	//[qbhy 18 100000000000]
}

更新语句

UpdateSql
package querybuilder

import (
	"fmt"
	"github.com/goal-web/contracts"
)

func TestUpdateSql() {
	sql, bindings := NewQuery("users").Where("id", ">", 1).UpdateSql(contracts.Fields{
		"name": "qbhy", "age": 18, "money": 100000000000,
	})
	fmt.Println(sql)
	fmt.Println(bindings)
    // update users set name = ?,age = ?,money = ? where id > ?
	// [qbhy 18 100000000000 1]
}

删除语句

DeleteSql
package querybuilder

import (
	"fmt"
)

func TestDeleteSql() {
	sql, bindings := NewQuery("users").Where("id", ">", 1).DeleteSql()
	fmt.Println(sql)
	fmt.Println(bindings)
    // delete from users where id > ?
    // [1]
}

更多高级用法

Laravel

彩蛋 ?

我正在开发一个像 laravel 那样的 Go web 开发框架,并且现在已经完成了大部分主要功能,如果你感兴趣的话,欢迎 star 持续跟踪最新动态
goal传送门