封装了自带的 database/sql 包
安装: go get github.com/jmoiron/sqlx
sqlx 类似database/sql,四个主要的处理类型
- sqlx.DB
- sqlx.Tx
- sqlx.Stmt
- sqlx.NamedStmt
两个游标类型
- sqlx.Rows
- sqlx.Row
连接数据库
- 前两个连接方式DB实例并不会去连接数据库
db = sqlx.Open("sqlite3", ":memory:")
db = sqlx.NewDb(db = sqlx.Open("sqlite3", ":memory:"))
err = db.Ping() //强制连接并测试它是否工作
- 打开一个DB并同时连接
db, err := sqlx.Connect("sqlite3", ":memory:")
- 打开、连接数据库的同时panic error
db = sqlx.MustConnect("sqlite3", ":memory:")
查询
- 未改变
Exec(...) (sql.Result, error)
- unchanged from database/sql
Query(...) (*sql.Rows, error)
- unchanged from database/sql
QueryRow(...) *sql.Row
- unchanged from database/sql - 对原生database/sql的扩展
MustExec() sql.Result
-- Exec, but panic on error
Queryx(...) (*sqlx.Rows, error)
- Query, but return an sqlx.Rows
QueryRowx(...) *sqlx.Row
-- QueryRow, but return an sqlx.Row - 新添加的语法
Get(dest interface{}, ...) error
Select(dest interface{}, ...) error
Exec 和 MustExec
schema := `CREATE TABLE place (
country text,
city text NULL,
telcode integer);`
// execute a query on the server
result, err := db.Exec(schema)
// or, you can use MustExec, which panics on error
cityState := `INSERT INTO place (country, telcode) VALUES (?, ?)`
countryCity := `INSERT INTO place (country, city, telcode) VALUES (?, ?, ?)`
db.MustExec(cityState, "Hong Kong", 852)
db.MustExec(cityState, "Singapore", 65)
db.MustExec(countryCity, "South Africa", "Johannesburg", 27)
? 是占位符 可以防止SQL注入攻击
MySQL uses the ? variant shown above
PostgreSQL uses an enumerated 2, etc bindvar syntax
SQLite accepts both ? and $1 syntax
Oracle uses a :name syntax
? 它们仅用于参数化,不允许更改SQL语句的结构
下面是两个错误的用法,并不能工作
db.Query("SELECT * FROM ?", "mytable")
db.Query("SELECT ?, ? FROM people", "name", "location")
Query 返回一个sql.Rows对象和一个error
// fetch all places from the db
rows, err := db.Query("SELECT country, city, telcode FROM place")
// iterate over each row
for rows.Next() {
var country string
// note that city can be NULL, so we use the NullString type
var city sql.NullString
var telcode int
err = rows.Scan(&country, &city, &telcode)
}
Rows更像是一个数据库游标,而不是实质化的结果列表。Scan()
使用reflect将sql列返回类型映射为Go类型,如string、[]byte等。
如果不迭代整个列表,确保调用 rows.Close()
通常返回的错误是由于SQL语法错误、类型不匹配或字段和表名不正确造成的。
查询所使用的连接一直处于活动状态,直到通过Next进行的迭代耗尽所有行,或者调用row.close()
,然后释放它。
Queryx sqlx扩展Queryx的行为与Query完全相同,但是返回一个sqlx.Rows
type Place struct {
Country string
City sql.NullString
TelephoneCode int `db:"telcode"`
}
rows, err := db.Queryx("SELECT * FROM place")
for rows.Next() {
var p Place
err = rows.StructScan(&p)
}
StructScan()
会自动将结果扫描到struct字段中。
struct 里的字段必须首字母大写,默认匹配 strings.Lower 数据库里的列名
StructScan, SliceScan, and MapScan
三种扫描方式
rows, err := db.Queryx("SELECT * FROM place")
for rows.Next() {
// cols is an []interface{} of all of the column results
cols, err := rows.SliceScan()
}
rows, err := db.Queryx("SELECT * FROM place")
for rows.Next() {
results := make(map[string]interface{})
err = rows.MapScan(results)
}
QueryRow
QueryRow从服务器获取一行
row := db.QueryRow("SELECT * FROM place WHERE telcode=?", 852)
var telcode int
err = row.Scan(&telcode)
与Query不同,QueryRow返回的是一个没有错误的Row类型结果,这样可以安全地将Scan与返回结果连接起来。如果执行查询时有错误,则Scan返回该错误。
QueryRowx 将返回一个sqlx.Row替换sql.Row
var p Place
err := db.QueryRowx("SELECT city, telcode FROM place LIMIT 1").StructScan(&p)
Get and Select
p := Place{}
pp := []Place{}
// this will pull the first place directly into p
err = db.Get(&p, "SELECT * FROM place LIMIT 1")
// this will pull places with telcode > 50 into the slice pp
err = db.Select(&pp, "SELECT * FROM place WHERE telcode > ?", 50)
// they work with regular types as well
var id int
err = db.Get(&id, "SELECT count(*) FROM place")
// fetch at most 10 place names
var names []string
err = db.Select(&names, "SELECT name FROM place LIMIT 10")
与Queryx不同,因为它将立即将整个结果集加载到内存中。如果该集合没有被查询限制到合理的大小,那么最好使用经典的Queryx/StructScan迭代。
事物
tx, err := db.Begin()
err = tx.Exec(...)
err = tx.Commit()
扩展Beginx()和MustBegin(),返回sqlx.Tx,而不是sql.Tx:
tx := db.MustBegin()
tx.MustExec(...)
err = tx.Commit()
Tx将在整个生命周期中维护该连接,只有在调用Commit()或Rollback()时才释放它
准备声明 sqlx.DB.Prepare()
可以显式地准备语句,以便在其他地方重用
stmt, err := db.Prepare(`SELECT * FROM place WHERE telcode=?`)
row = stmt.QueryRow(65)
tx, err := db.Begin()
txStmt, err := tx.Prepare(`SELECT * FROM place WHERE telcode=?`)
row = txStmt.QueryRow(852)
Prepare实际上在数据库上运行准备,因此它需要一个连接及其连接状态。
stmt, err := db.Preparex(`SELECT * FROM place WHERE telcode=?`)
var p Place
err = stmt.Get(&p, 852)
Query Helpers
- "In" Queries
方法一
var levels = []int{4, 6, 7}
rows, err := db.Query("SELECT * FROM users WHERE level IN (?);", levels)
方法二
var levels = []int{4, 6, 7}
query, args, err := sqlx.In("SELECT * FROM users WHERE level IN (?);", levels)
// sqlx.In returns queries with the `?` bindvar, we can rebind it for our backend
query = db.Rebind(query)
rows, err := db.Query(query, args...)