# package sql
`import "database/sql"`
sql包提供了保證SQL或類SQL數據庫的泛用接口。
使用sql包時必須注入(至少)一個數據庫驅動。參見[http://golang.org/s/sqldrivers](http://golang.org/s/sqldrivers) 獲取驅動列表。
更多用法示例,參見wiki頁面:[http://golang.org/s/sqlwiki](http://golang.org/s/sqlwiki)。
## Index
* [Variables](#pkg-variables)
* [type Scanner](#Scanner)
* [type NullBool](#NullBool)
* [func (n \*NullBool) Scan(value interface{}) error](#NullBool.Scan)
* [func (n NullBool) Value() (driver.Value, error)](#NullBool.Value)
* [type NullInt64](#NullInt64)
* [func (n \*NullInt64) Scan(value interface{}) error](#NullInt64.Scan)
* [func (n NullInt64) Value() (driver.Value, error)](#NullInt64.Value)
* [type NullFloat64](#NullFloat64)
* [func (n \*NullFloat64) Scan(value interface{}) error](#NullFloat64.Scan)
* [func (n NullFloat64) Value() (driver.Value, error)](#NullFloat64.Value)
* [type NullString](#NullString)
* [func (ns \*NullString) Scan(value interface{}) error](#NullString.Scan)
* [func (ns NullString) Value() (driver.Value, error)](#NullString.Value)
* [type RawBytes](#RawBytes)
* [type Result](#Result)
* [type DB](#DB)
* [func Open(driverName, dataSourceName string) (\*DB, error)](#Open)
* [func (db \*DB) Driver() driver.Driver](#DB.Driver)
* [func (db \*DB) Ping() error](#DB.Ping)
* [func (db \*DB) Close() error](#DB.Close)
* [func (db \*DB) SetMaxOpenConns(n int)](#DB.SetMaxOpenConns)
* [func (db \*DB) SetMaxIdleConns(n int)](#DB.SetMaxIdleConns)
* [func (db \*DB) Exec(query string, args ...interface{}) (Result, error)](#DB.Exec)
* [func (db \*DB) Query(query string, args ...interface{}) (\*Rows, error)](#DB.Query)
* [func (db \*DB) QueryRow(query string, args ...interface{}) \*Row](#DB.QueryRow)
* [func (db \*DB) Prepare(query string) (\*Stmt, error)](#DB.Prepare)
* [func (db \*DB) Begin() (\*Tx, error)](#DB.Begin)
* [type Row](#Row)
* [func (r \*Row) Scan(dest ...interface{}) error](#Row.Scan)
* [type Rows](#Rows)
* [func (rs \*Rows) Columns() ([]string, error)](#Rows.Columns)
* [func (rs \*Rows) Scan(dest ...interface{}) error](#Rows.Scan)
* [func (rs \*Rows) Next() bool](#Rows.Next)
* [func (rs \*Rows) Close() error](#Rows.Close)
* [func (rs \*Rows) Err() error](#Rows.Err)
* [type Stmt](#Stmt)
* [func (s \*Stmt) Exec(args ...interface{}) (Result, error)](#Stmt.Exec)
* [func (s \*Stmt) Query(args ...interface{}) (\*Rows, error)](#Stmt.Query)
* [func (s \*Stmt) QueryRow(args ...interface{}) \*Row](#Stmt.QueryRow)
* [func (s \*Stmt) Close() error](#Stmt.Close)
* [type Tx](#Tx)
* [func (tx \*Tx) Exec(query string, args ...interface{}) (Result, error)](#Tx.Exec)
* [func (tx \*Tx) Query(query string, args ...interface{}) (\*Rows, error)](#Tx.Query)
* [func (tx \*Tx) QueryRow(query string, args ...interface{}) \*Row](#Tx.QueryRow)
* [func (tx \*Tx) Prepare(query string) (\*Stmt, error)](#Tx.Prepare)
* [func (tx \*Tx) Stmt(stmt \*Stmt) \*Stmt](#Tx.Stmt)
* [func (tx \*Tx) Commit() error](#Tx.Commit)
* [func (tx \*Tx) Rollback() error](#Tx.Rollback)
* [func Register(name string, driver driver.Driver)](#Register)
### Examples
* [DB.Query](#example-DB-Query)
* [DB.QueryRow](#example-DB-QueryRow)
## Variables
```
var ErrNoRows = errors.New("sql: no rows in result set")
```
當QueryRow方法沒有返回一個row時,調用返回值的Scan方法會返回ErrNoRows。此時,QueryRow返回一個占位的\*Row值,延遲本錯誤直到調用Scan方法時才釋放。
```
var ErrTxDone = errors.New("sql: Transaction has already been committed or rolled back")
```
## func [Register](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L30 "View Source")
```
func Register(name string, driver driver.Driver)
```
Register注冊并命名一個數據庫,可以在Open函數中使用該命名啟用該驅動。如果 Register注冊同一名稱兩次,或者driver參數為nil,會導致panic。
## type [Scanner](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L160 "View Source")
```
type Scanner interface {
// Scan方法從數據庫驅動獲取一個值。
//
// 參數src的類型保證為如下類型之一:
//
// int64
// float64
// bool
// []byte
// string
// time.Time
// nil - 表示NULL值
//
// 如果不能不丟失信息的保存一個值,應返回錯誤。
Scan(src interface{}) error
}
```
Scanner接口會被Rows或Row的Scan方法使用。
## type [NullBool](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L136 "View Source")
```
type NullBool struct {
Bool bool
Valid bool // 如果Bool不是NULL則Valid為真
}
```
NullBool代表一個可為NULL的布爾值。NullBool實現了Scanner接口,因此可以作為Rows/Row的Scan方法的參數保存掃描結果,類似NullString。
### func (\*NullBool) [Scan](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L142 "View Source")
```
func (n *NullBool) Scan(value interface{}) error
```
Scan實現了Scanner接口。
### func (NullBool) [Value](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L152 "View Source")
```
func (n NullBool) Value() (driver.Value, error)
```
Value實現了driver.Valuer接口。
## type [NullInt64](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L84 "View Source")
```
type NullInt64 struct {
Int64 int64
Valid bool // 如果Int64不是NULL則Valid為真
}
```
NullInt64代表一個可為NULL的int64值。NullInt64實現了Scanner接口,因此可以作為Rows/Row的Scan方法的參數保存掃描結果,類似NullString。
### func (\*NullInt64) [Scan](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L90 "View Source")
```
func (n *NullInt64) Scan(value interface{}) error
```
Scan實現了Scanner接口。
### func (NullInt64) [Value](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L100 "View Source")
```
func (n NullInt64) Value() (driver.Value, error)
```
Value實現了driver.Valuer接口。
## type [NullFloat64](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L110 "View Source")
```
type NullFloat64 struct {
Float64 float64
Valid bool // 如果Float64不是NULL則Valid為真
}
```
NullFloat64代表一個可為NULL的float64值。NullFloat64實現了Scanner接口,因此可以作為Rows/Row的Scan方法的參數保存掃描結果,類似NullString。
### func (\*NullFloat64) [Scan](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L116 "View Source")
```
func (n *NullFloat64) Scan(value interface{}) error
```
Scan實現了Scanner接口。
### func (NullFloat64) [Value](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L126 "View Source")
```
func (n NullFloat64) Value() (driver.Value, error)
```
Value實現了driver.Valuer接口。
## type [NullString](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L58 "View Source")
```
type NullString struct {
String string
Valid bool // 如果String不是NULL則Valid為真
}
```
NullString代表一個可為NULL的字符串。NullString實現了Scanner接口,因此可以作為Rows/Row的Scan方法的參數保存掃描結果:
```
var s NullString
err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
...
if s.Valid {
// use s.String
} else {
// NULL value
}
```
### func (\*NullString) [Scan](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L64 "View Source")
```
func (ns *NullString) Scan(value interface{}) error
```
Scan實現了Scanner接口。
### func (NullString) [Value](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L74 "View Source")
```
func (ns NullString) Value() (driver.Value, error)
```
Value實現了driver.Valuer接口。
## type [RawBytes](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L43 "View Source")
```
type RawBytes []byte
```
RawBytes是一個字節切片,保管對內存的引用,為數據庫自身所使用。在Scaner接口的Scan方法寫入RawBytes數據后,該切片只在限次調用Next、Scan或Close方法之前合法。
## type [Result](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1679 "View Source")
```
type Result interface {
// LastInsertId返回一個數據庫生成的回應命令的整數。
// 當插入新行時,一般來自一個"自增"列。
// 不是所有的數據庫都支持該功能,該狀態的語法也各有不同。
LastInsertId() (int64, error)
// RowsAffected返回被update、insert或delete命令影響的行數。
// 不是所有的數據庫都支持該功能。
RowsAffected() (int64, error)
}
```
Result是對已執行的SQL命令的總結。
## type [DB](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L196 "View Source")
```
type DB struct {
// 內含隱藏或非導出字段
}
```
DB是一個數據庫(操作)句柄,代表一個具有零到多個底層連接的連接池。它可以安全的被多個go程同時使用。
sql包會自動創建和釋放連接;它也會維護一個閑置連接的連接池。如果數據庫具有單連接狀態的概念,該狀態只有在事務中被觀察時才可信。一旦調用了BD.Begin,返回的Tx會綁定到單個連接。當調用事務Tx的Commit或Rollback后,該事務使用的連接會歸還到DB的閑置連接池中。連接池的大小可以用SetMaxIdleConns方法控制。
### func [Open](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L429 "View Source")
```
func Open(driverName, dataSourceName string) (*DB, error)
```
Open打開一個dirverName指定的數據庫,dataSourceName指定數據源,一般包至少括數據庫文件名和(可能的)連接信息。
大多數用戶會通過數據庫特定的連接幫助函數打開數據庫,返回一個\*DB。Go標準庫中沒有數據庫驅動。參見[http://golang.org/s/sqldrivers](http://golang.org/s/sqldrivers)獲取第三方驅動。
Open函數可能只是驗證其參數,而不創建與數據庫的連接。如果要檢查數據源的名稱是否合法,應調用返回值的Ping方法。
返回的DB可以安全的被多個go程同時使用,并會維護自身的閑置連接池。這樣一來,Open函數只需調用一次。很少需要關閉DB。
### func (\*DB) [Driver](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1031 "View Source")
```
func (db *DB) Driver() driver.Driver
```
Driver方法返回數據庫下層驅動。
### func (\*DB) [Ping](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L448 "View Source")
```
func (db *DB) Ping() error
```
Ping檢查與數據庫的連接是否仍有效,如果需要會創建連接。
### func (\*DB) [Close](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L464 "View Source")
```
func (db *DB) Close() error
```
Close關閉數據庫,釋放任何打開的資源。一般不會關閉DB,因為DB句柄通常被多個go程共享,并長期活躍。
### func (\*DB) [SetMaxOpenConns](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L550 "View Source")
```
func (db *DB) SetMaxOpenConns(n int)
```
SetMaxOpenConns設置與數據庫建立連接的最大數目。
如果n大于0且小于最大閑置連接數,會將最大閑置連接數減小到匹配最大開啟連接數的限制。
如果n <= 0,不會限制最大開啟連接數,默認為0(無限制)。
### func (\*DB) [SetMaxIdleConns](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L517 "View Source")
```
func (db *DB) SetMaxIdleConns(n int)
```
SetMaxIdleConns設置連接池中的最大閑置連接數。
如果n大于最大開啟連接數,則新的最大閑置連接數會減小到匹配最大開啟連接數的限制。
如果n <= 0,不會保留閑置連接。
### func (\*DB) [Exec](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L862 "View Source")
```
func (db *DB) Exec(query string, args ...interface{}) (Result, error)
```
Exec執行一次命令(包括查詢、刪除、更新、插入等),不返回任何執行結果。參數args表示query中的占位參數。
### func (\*DB) [Query](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L911 "View Source")
```
func (db *DB) Query(query string, args ...interface{}) (*Rows, error)
```
Query執行一次查詢,返回多行結果(即Rows),一般用于執行select命令。參數args表示query中的占位參數。
Example
```
age := 27
rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
log.Fatal(err)
}
fmt.Printf("%s is %d\n", name, age)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
```
### func (\*DB) [QueryRow](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L992 "View Source")
```
func (db *DB) QueryRow(query string, args ...interface{}) *Row
```
QueryRow執行一次查詢,并期望返回最多一行結果(即Row)。QueryRow總是返回非nil的值,直到返回值的Scan方法被調用時,才會返回被延遲的錯誤。(如:未找到結果)
Example
```
id := 123
var username string
err := db.QueryRow("SELECT username FROM users WHERE id=?", id).Scan(&username)
switch {
case err == sql.ErrNoRows:
log.Printf("No user with that ID.")
case err != nil:
log.Fatal(err)
default:
fmt.Printf("Username is %s\n", username)
}
```
### func (\*DB) [Prepare](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L820 "View Source")
```
func (db *DB) Prepare(query string) (*Stmt, error)
```
Prepare創建一個準備好的狀態用于之后的查詢和命令。返回值可以同時執行多個查詢和命令。
### func (\*DB) [Begin](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L999 "View Source")
```
func (db *DB) Begin() (*Tx, error)
```
Begin開始一個事務。隔離水平由數據庫驅動決定。
## type [Row](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1625 "View Source")
```
type Row struct {
// 內含隱藏或非導出字段
}
```
QueryRow方法返回Row,代表單行查詢結果。
### func (\*Row) [Scan](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1635 "View Source")
```
func (r *Row) Scan(dest ...interface{}) error
```
Scan將該行查詢結果各列分別保存進dest參數指定的值中。如果該查詢匹配多行,Scan會使用第一行結果并丟棄其余各行。如果沒有匹配查詢的行,Scan會返回ErrNoRows。
## type [Rows](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1518 "View Source")
```
type Rows struct {
// 內含隱藏或非導出字段
}
```
Rows是查詢的結果。它的游標指向結果集的第零行,使用Next方法來遍歷各行結果:
```
rows, err := db.Query("SELECT ...")
...
defer rows.Close()
for rows.Next() {
var id int
var name string
err = rows.Scan(&id, &name)
...
}
err = rows.Err() // get any error encountered during iteration
...
```
### func (\*Rows) [Columns](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1562 "View Source")
```
func (rs *Rows) Columns() ([]string, error)
```
Columns返回列名。如果Rows已經關閉會返回錯誤。
### func (\*Rows) [Scan](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1584 "View Source")
```
func (rs *Rows) Scan(dest ...interface{}) error
```
Scan將當前行各列結果填充進dest指定的各個值中。
如果某個參數的類型為*[]byte,Scan會保存對應數據的拷貝,該拷貝為調用者所有,可以安全的,修改或無限期的保存。如果參數類型為\*RawBytes可以避免拷貝;參見RawBytes的文檔獲取其使用的約束。
如果某個參數的類型為\*interface{},Scan會不做轉換的拷貝底層驅動提供的值。如果值的類型為[]byte,會進行數據的拷貝,調用者可以安全使用該值。
### func (\*Rows) [Next](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1535 "View Source")
```
func (rs *Rows) Next() bool
```
Next準備用于Scan方法的下一行結果。如果成功會返回真,如果沒有下一行或者出現錯誤會返回假。Err應該被調用以區分這兩種情況。
每一次調用Scan方法,甚至包括第一次調用該方法,都必須在前面先調用Next方法。
### func (\*Rows) [Close](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1608 "View Source")
```
func (rs *Rows) Close() error
```
Close關閉Rows,阻止對其更多的列舉。 如果Next方法返回假,Rows會自動關閉,滿足。檢查Err方法結果的條件。Close方法時冪等的(多次調用無效的成功),不影響Err方法的結果。
### func (\*Rows) [Err](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1552 "View Source")
```
func (rs *Rows) Err() error
```
Err返回可能的、在迭代時出現的錯誤。Err需在顯式或隱式調用Close方法后調用。
## type [Stmt](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1237 "View Source")
```
type Stmt struct {
// 內含隱藏或非導出字段
}
```
Stmt是準備好的狀態。Stmt可以安全的被多個go程同時使用。
### func (\*Stmt) [Exec](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1261 "View Source")
```
func (s *Stmt) Exec(args ...interface{}) (Result, error)
```
Exec使用提供的參數執行準備好的命令狀態,返回Result類型的該狀態執行結果的總結。
### func (\*Stmt) [Query](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1382 "View Source")
```
func (s *Stmt) Query(args ...interface{}) (*Rows, error)
```
Query使用提供的參數執行準備好的查詢狀態,返回Rows類型查詢結果。
### func (\*Stmt) [QueryRow](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1458 "View Source")
```
func (s *Stmt) QueryRow(args ...interface{}) *Row
```
QueryRow使用提供的參數執行準備好的查詢狀態。如果在執行時遇到了錯誤,該錯誤會被延遲,直到返回值的Scan方法被調用時才釋放。返回值總是非nil的。如果沒有查詢到結果,\*Row類型返回值的Scan方法會返回ErrNoRows;否則,Scan方法會掃描結果第一行并丟棄其余行。
示例用法:
```
var name string
err := nameByUseridStmt.QueryRow(id).Scan(&name)
```
### func (\*Stmt) [Close](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1467 "View Source")
```
func (s *Stmt) Close() error
```
Close關閉狀態。
## type [Tx](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1041 "View Source")
```
type Tx struct {
// 內含隱藏或非導出字段
}
```
Tx代表一個進行中的數據庫事務。
一次事務必須以對Commit或Rollback的調用結束。
調用Commit或Rollback后,所有對事務的操作都會失敗并返回錯誤值ErrTxDone。
### func (\*Tx) [Exec](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1179 "View Source")
```
func (tx *Tx) Exec(query string, args ...interface{}) (Result, error)
```
Exec執行命令,但不返回結果。例如執行insert和update。
### func (\*Tx) [Query](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1213 "View Source")
```
func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error)
```
Query執行查詢并返回零到多行結果(Rows),一般執行select命令。
### func (\*Tx) [QueryRow](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1225 "View Source")
```
func (tx *Tx) QueryRow(query string, args ...interface{}) *Row
```
QueryRow執行查詢并期望返回最多一行結果(Row)。QueryRow總是返回非nil的結果,查詢失敗的錯誤會延遲到在調用該結果的Scan方法時釋放。
### func (\*Tx) [Prepare](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1102 "View Source")
```
func (tx *Tx) Prepare(query string) (*Stmt, error)
```
Prepare準備一個專用于該事務的狀態。返回的該事務專屬狀態操作在Tx遞交會回滾后不能再使用。要在該事務中使用已存在的狀態,參見Tx.Stmt方法。
### func (\*Tx) [Stmt](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1149 "View Source")
```
func (tx *Tx) Stmt(stmt *Stmt) *Stmt
```
Stmt使用已存在的狀態生成一個該事務特定的狀態。
示例:
```
updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
...
tx, err := db.Begin()
...
res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
```
### func (\*Tx) [Commit](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1075 "View Source")
```
func (tx *Tx) Commit() error
```
Commit遞交事務。
### func (\*Tx) [Rollback](https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1086 "View Source")
```
func (tx *Tx) Rollback() error
```
Rollback放棄并回滾事務。
- 庫
- package achive
- package tar
- package zip
- package bufio
- package builtin
- package bytes
- package compress
- package bzip2
- package flate
- package gzip
- package lzw
- package zlib
- package container
- package heap
- package list
- package ring
- package crypto
- package aes
- package cipher
- package des
- package dsa
- package ecdsa
- package elliptic
- package hmac
- package md5
- package rand
- package rc4
- package rsa
- package sha1
- package sha256
- package sha512
- package subtle
- package tls
- package x509
- package pkix
- package database
- package sql
- package driver
- package encoding
- package ascii85
- package asn1
- package base32
- package base64
- package binary
- package csv
- package gob
- package hex
- package json
- package pem
- package xml
- package errors
- package expvar
- package flag
- package fmt
- package go
- package doc
- package format
- package parser
- package printer
- package hash
- package adler32
- package crc32
- package crc64
- package fnv
- package html
- package template
- package image
- package color
- package palette
- package draw
- package gif
- package jpeg
- package png
- package index
- package suffixarray
- package io
- package ioutil
- package log
- package syslog
- package math
- package big
- package cmplx
- package rand
- package mime
- package multipart
- package net
- package http
- package cgi
- package cookiejar
- package fcgi
- package httptest
- package httputil
- package pprof
- package mail
- package rpc
- package jsonrpc
- package smtp
- package textproto
- package url
- package os
- package exec
- package signal
- package user
- package path
- package filepath
- package reflect
- package regexp
- package runtime
- package cgo
- package debug
- package pprof
- package race
- package sort
- package strconv
- package strings
- package sync
- package atomic
- package text
- package scanner
- package tabwriter
- package template
- package time
- package unicode
- package utf16
- package utf8
- package unsafe