version: 1.10

package sql

import "database/sql"

Overview

Package sql provides a generic interface around SQL (or SQL-like) databases.

The sql package must be used in conjunction with a database driver. See
https://golang.org/s/sqldrivers for a list of drivers.

Drivers that do not support context cancelation will not return until after the
query is completed.

For usage examples, see the wiki page at https://golang.org/s/sqlwiki.

Index

Examples

Package files

convert.go ctxutil.go sql.go

Variables

  1. var ErrConnDone = errors.New("database/sql: connection is already closed")

ErrConnDone is returned by any operation that is performed on a connection that
has already been returned to the connection pool.

  1. var ErrNoRows = errors.New("sql: no rows in result set")

ErrNoRows is returned by Scan when QueryRow doesn’t return a row. In such a
case, QueryRow returns a placeholder *Row value that defers this error until a
Scan.

  1. var ErrTxDone = errors.New("sql: Transaction has already been committed or rolled back")

ErrTxDone is returned by any operation that is performed on a transaction that
has already been committed or rolled back.

func Drivers

  1. func Drivers() []string

Drivers returns a sorted list of the names of the registered drivers.

func Register

  1. func Register(name string, driver driver.Driver)

Register makes a database driver available by the provided name. If Register is
called twice with the same name or if driver is nil, it panics.

type ColumnType

  1. type ColumnType struct {
  2. // contains filtered or unexported fields
  3. }

ColumnType contains the name and type of a column.

func (*ColumnType) DatabaseTypeName

  1. func (ci *ColumnType) DatabaseTypeName() string

DatabaseTypeName returns the database system name of the column type. If an
empty string is returned the driver type name is not supported. Consult your
driver documentation for a list of driver data types. Length specifiers are not
included. Common type include “VARCHAR”, “TEXT”, “NVARCHAR”, “DECIMAL”, “BOOL”,
“INT”, “BIGINT”.

func (*ColumnType) DecimalSize

  1. func (ci *ColumnType) DecimalSize() (precision, scale int64, ok bool)

DecimalSize returns the scale and precision of a decimal type. If not applicable
or if not supported ok is false.

func (*ColumnType) Length

  1. func (ci *ColumnType) Length() (length int64, ok bool)

Length returns the column type length for variable length column types such as
text and binary field types. If the type length is unbounded the value will be
math.MaxInt64 (any database limits will still apply). If the column type is not
variable length, such as an int, or if not supported by the driver ok is false.

func (*ColumnType) Name

  1. func (ci *ColumnType) Name() string

Name returns the name or alias of the column.

func (*ColumnType) Nullable

  1. func (ci *ColumnType) Nullable() (nullable, ok bool)

Nullable returns whether the column may be null. If a driver does not support
this property ok will be false.

func (*ColumnType) ScanType

  1. func (ci *ColumnType) ScanType() reflect.Type

ScanType returns a Go type suitable for scanning into using Rows.Scan. If a
driver does not support this property ScanType will return the type of an empty
interface.

type Conn

  1. type Conn struct {
  2. // contains filtered or unexported fields
  3. }

Conn represents a single database connection rather than a pool of database
connections. Prefer running queries from DB unless there is a specific need for
a continuous single database connection.

A Conn must call Close to return the connection to the database pool and may do
so concurrently with a running query.

After a call to Close, all operations on the connection fail with ErrConnDone.

func (*Conn) BeginTx

  1. func (c *Conn) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error)

BeginTx starts a transaction.

The provided context is used until the transaction is committed or rolled back.
If the context is canceled, the sql package will roll back the transaction.
Tx.Commit will return an error if the context provided to BeginTx is canceled.

The provided TxOptions is optional and may be nil if defaults should be used. If
a non-default isolation level is used that the driver doesn’t support, an error
will be returned.

func (*Conn) Close

  1. func (c *Conn) Close() error

Close returns the connection to the connection pool. All operations after a
Close will return with ErrConnDone. Close is safe to call concurrently with
other operations and will block until all other operations finish. It may be
useful to first cancel any used context and then call close directly after.

func (*Conn) ExecContext

  1. func (c *Conn) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error)

ExecContext executes a query without returning any rows. The args are for any
placeholder parameters in the query.

func (*Conn) PingContext

  1. func (c *Conn) PingContext(ctx context.Context) error

PingContext verifies the connection to the database is still alive.

func (*Conn) PrepareContext

  1. func (c *Conn) PrepareContext(ctx context.Context, query string) (*Stmt, error)

PrepareContext creates a prepared statement for later queries or executions.
Multiple queries or executions may be run concurrently from the returned
statement. The caller must call the statement’s Close method when the statement
is no longer needed.

The provided context is used for the preparation of the statement, not for the
execution of the statement.

func (*Conn) QueryContext

  1. func (c *Conn) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)

QueryContext executes a query that returns rows, typically a SELECT. The args
are for any placeholder parameters in the query.

func (*Conn) QueryRowContext

  1. func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row

QueryRowContext executes a query that is expected to return at most one row.
QueryRowContext always returns a non-nil value. Errors are deferred until Row’s
Scan method is called. If the query selects no rows, the Row’s Scan will return
ErrNoRows. Otherwise, the
Row’s Scan scans the first selected row and discards
the rest.

type DB

  1. type DB struct {
  2. // contains filtered or unexported fields
  3. }

DB is a database handle representing a pool of zero or more underlying
connections. It’s safe for concurrent use by multiple goroutines.

The sql package creates and frees connections automatically; it also maintains a
free pool of idle connections. If the database has a concept of per-connection
state, such state can only be reliably observed within a transaction. Once
DB.Begin is called, the returned Tx is bound to a single connection. Once Commit
or Rollback is called on the transaction, that transaction’s connection is
returned to DB’s idle connection pool. The pool size can be controlled with
SetMaxIdleConns.

func Open

  1. func Open(driverName, dataSourceName string) (*DB, error)

Open opens a database specified by its database driver name and a
driver-specific data source name, usually consisting of at least a database name
and connection information.

Most users will open a database via a driver-specific connection helper function
that returns a *DB. No database drivers are included in the Go standard library.
See https://golang.org/s/sqldrivers for a list of third-party drivers.

Open may just validate its arguments without creating a connection to the
database. To verify that the data source name is valid, call Ping.

The returned DB is safe for concurrent use by multiple goroutines and maintains
its own pool of idle connections. Thus, the Open function should be called just
once. It is rarely necessary to close a DB.

func OpenDB

  1. func OpenDB(c driver.Connector) *DB

OpenDB opens a database using a Connector, allowing drivers to bypass a string
based data source name.

Most users will open a database via a driver-specific connection helper function
that returns a *DB. No database drivers are included in the Go standard library.
See https://golang.org/s/sqldrivers for a list of third-party drivers.

OpenDB may just validate its arguments without creating a connection to the
database. To verify that the data source name is valid, call Ping.

The returned DB is safe for concurrent use by multiple goroutines and maintains
its own pool of idle connections. Thus, the OpenDB function should be called
just once. It is rarely necessary to close a DB.

func (*DB) Begin

  1. func (db *DB) Begin() (*Tx, error)

Begin starts a transaction. The default isolation level is dependent on the
driver.

func (*DB) BeginTx

  1. func (db *DB) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error)

BeginTx starts a transaction.

The provided context is used until the transaction is committed or rolled back.
If the context is canceled, the sql package will roll back the transaction.
Tx.Commit will return an error if the context provided to BeginTx is canceled.

The provided TxOptions is optional and may be nil if defaults should be used. If
a non-default isolation level is used that the driver doesn’t support, an error
will be returned.

func (*DB) Close

  1. func (db *DB) Close() error

Close closes the database, releasing any open resources.

It is rare to Close a DB, as the DB handle is meant to be long-lived and shared
between many goroutines.

func (*DB) Conn

  1. func (db *DB) Conn(ctx context.Context) (*Conn, error)

Conn returns a single connection by either opening a new connection or returning
an existing connection from the connection pool. Conn will block until either a
connection is returned or ctx is canceled. Queries run on the same Conn will be
run in the same database session.

Every Conn must be returned to the database pool after use by calling
Conn.Close.

func (*DB) Driver

  1. func (db *DB) Driver() driver.Driver

Driver returns the database’s underlying driver.

func (*DB) Exec

  1. func (db *DB) Exec(query string, args ...interface{}) (Result, error)

Exec executes a query without returning any rows. The args are for any
placeholder parameters in the query.

func (*DB) ExecContext

  1. func (db *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error)

ExecContext executes a query without returning any rows. The args are for any
placeholder parameters in the query.

func (*DB) Ping

  1. func (db *DB) Ping() error

Ping verifies a connection to the database is still alive, establishing a
connection if necessary.

func (*DB) PingContext

  1. func (db *DB) PingContext(ctx context.Context) error

PingContext verifies a connection to the database is still alive, establishing a
connection if necessary.

func (*DB) Prepare

  1. func (db *DB) Prepare(query string) (*Stmt, error)

Prepare creates a prepared statement for later queries or executions. Multiple
queries or executions may be run concurrently from the returned statement. The
caller must call the statement’s Close method when the statement is no longer
needed.

func (*DB) PrepareContext

  1. func (db *DB) PrepareContext(ctx context.Context, query string) (*Stmt, error)

PrepareContext creates a prepared statement for later queries or executions.
Multiple queries or executions may be run concurrently from the returned
statement. The caller must call the statement’s Close method when the statement
is no longer needed.

The provided context is used for the preparation of the statement, not for the
execution of the statement.

func (*DB) Query

  1. func (db *DB) Query(query string, args ...interface{}) (*Rows, error)

Query executes a query that returns rows, typically a SELECT. The args are for
any placeholder parameters in the query.


Example:

  1. age := 27
  2. rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. defer rows.Close()
  7. for rows.Next() {
  8. var name string
  9. if err := rows.Scan(&name); err != nil {
  10. log.Fatal(err)
  11. }
  12. fmt.Printf("%s is %d\n", name, age)
  13. }
  14. if err := rows.Err(); err != nil {
  15. log.Fatal(err)
  16. }


Example:

  1. age := 27
  2. q := `
  3. create temp table uid (id bigint); -- Create temp table for queries.
  4. insert into uid
  5. select id from users where age < ?; -- Populate temp table.
  6. -- First result set.
  7. select
  8. users.id, name
  9. from
  10. users
  11. join uid on users.id = uid.id
  12. ;
  13. -- Second result set.
  14. select
  15. ur.user, ur.role
  16. from
  17. user_roles as ur
  18. join uid on uid.id = ur.user
  19. ;
  20. `
  21. rows, err := db.Query(q, age)
  22. if err != nil {
  23. log.Fatal(err)
  24. }
  25. defer rows.Close()
  26. for rows.Next() {
  27. var (
  28. id int64
  29. name string
  30. )
  31. if err := rows.Scan(&id, &name); err != nil {
  32. log.Fatal(err)
  33. }
  34. fmt.Printf("id %d name is %s\n", id, name)
  35. }
  36. if !rows.NextResultSet() {
  37. log.Fatal("expected more result sets", rows.Err())
  38. }
  39. var roleMap = map[int64]string{
  40. 1: "user",
  41. 2: "admin",
  42. 3: "gopher",
  43. }
  44. for rows.Next() {
  45. var (
  46. id int64
  47. role int64
  48. )
  49. if err := rows.Scan(&id, &role); err != nil {
  50. log.Fatal(err)
  51. }
  52. fmt.Printf("id %d has role %s\n", id, roleMap[role])
  53. }
  54. if err := rows.Err(); err != nil {
  55. log.Fatal(err)
  56. }

func (*DB) QueryContext

  1. func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)

QueryContext executes a query that returns rows, typically a SELECT. The args
are for any placeholder parameters in the query.

func (*DB) QueryRow

  1. func (db *DB) QueryRow(query string, args ...interface{}) *Row

QueryRow executes a query that is expected to return at most one row. QueryRow
always returns a non-nil value. Errors are deferred until Row’s Scan method is
called. If the query selects no rows, the Row’s Scan will return ErrNoRows.
Otherwise, the
Row’s Scan scans the first selected row and discards the rest.


Example:

  1. id := 123
  2. var username string
  3. err := db.QueryRow("SELECT username FROM users WHERE id=?", id).Scan(&username)
  4. switch {
  5. case err == sql.ErrNoRows:
  6. log.Printf("No user with that ID.")
  7. case err != nil:
  8. log.Fatal(err)
  9. default:
  10. fmt.Printf("Username is %s\n", username)
  11. }

func (*DB) QueryRowContext

  1. func (db *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row

QueryRowContext executes a query that is expected to return at most one row.
QueryRowContext always returns a non-nil value. Errors are deferred until Row’s
Scan method is called. If the query selects no rows, the Row’s Scan will return
ErrNoRows. Otherwise, the
Row’s Scan scans the first selected row and discards
the rest.

func (*DB) SetConnMaxLifetime

  1. func (db *DB) SetConnMaxLifetime(d time.Duration)

SetConnMaxLifetime sets the maximum amount of time a connection may be reused.

Expired connections may be closed lazily before reuse.

If d <= 0, connections are reused forever.

func (*DB) SetMaxIdleConns

  1. func (db *DB) SetMaxIdleConns(n int)

SetMaxIdleConns sets the maximum number of connections in the idle connection
pool.

If MaxOpenConns is greater than 0 but less than the new MaxIdleConns then the
new MaxIdleConns will be reduced to match the MaxOpenConns limit

If n <= 0, no idle connections are retained.

func (*DB) SetMaxOpenConns

  1. func (db *DB) SetMaxOpenConns(n int)

SetMaxOpenConns sets the maximum number of open connections to the database.

If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than
MaxIdleConns, then MaxIdleConns will be reduced to match the new MaxOpenConns
limit

If n <= 0, then there is no limit on the number of open connections. The default
is 0 (unlimited).

func (*DB) Stats

  1. func (db *DB) Stats() DBStats

Stats returns database statistics.

type DBStats

  1. type DBStats struct {
  2. // OpenConnections is the number of open connections to the database.
  3. OpenConnections int
  4. }

DBStats contains database statistics.

type IsolationLevel

  1. type IsolationLevel int

IsolationLevel is the transaction isolation level used in TxOptions.

  1. const (
  2. LevelDefault IsolationLevel = iota
  3. LevelReadUncommitted
  4. LevelReadCommitted
  5. LevelWriteCommitted
  6. LevelRepeatableRead
  7. LevelSnapshot
  8. LevelSerializable
  9. LevelLinearizable
  10. )

Various isolation levels that drivers may support in BeginTx. If a driver does
not support a given isolation level an error may be returned.

See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.

type NamedArg

  1. type NamedArg struct {
  2.  
  3. // Name is the name of the parameter placeholder.
  4. //
  5. // If empty, the ordinal position in the argument list will be
  6. // used.
  7. //
  8. // Name must omit any symbol prefix.
  9. Name string
  10.  
  11. // Value is the value of the parameter.
  12. // It may be assigned the same value types as the query
  13. // arguments.
  14. Value interface{}
  15. // contains filtered or unexported fields
  16. }

A NamedArg is a named argument. NamedArg values may be used as arguments to
Query or Exec and bind to the corresponding named parameter in the SQL
statement.

For a more concise way to create NamedArg values, see the Named function.

func Named

  1. func Named(name string, value interface{}) NamedArg

Named provides a more concise way to create NamedArg values.

Example usage:

  1. db.ExecContext(ctx, `
  2. delete from Invoice
  3. where
  4. TimeCreated < @end
  5. and TimeCreated >= @start;`,
  6. sql.Named("start", startTime),
  7. sql.Named("end", endTime),
  8. )

type NullBool

  1. type NullBool struct {
  2. Bool bool
  3. Valid bool // Valid is true if Bool is not NULL
  4. }

NullBool represents a bool that may be null. NullBool implements the Scanner
interface so it can be used as a scan destination, similar to NullString.

func (*NullBool) Scan

  1. func (n *NullBool) Scan(value interface{}) error

Scan implements the Scanner interface.

func (NullBool) Value

  1. func (n NullBool) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type NullFloat64

  1. type NullFloat64 struct {
  2. Float64 float64
  3. Valid bool // Valid is true if Float64 is not NULL
  4. }

NullFloat64 represents a float64 that may be null. NullFloat64 implements the
Scanner interface so it can be used as a scan destination, similar to
NullString.

func (*NullFloat64) Scan

  1. func (n *NullFloat64) Scan(value interface{}) error

Scan implements the Scanner interface.

func (NullFloat64) Value

  1. func (n NullFloat64) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type NullInt64

  1. type NullInt64 struct {
  2. Int64 int64
  3. Valid bool // Valid is true if Int64 is not NULL
  4. }

NullInt64 represents an int64 that may be null. NullInt64 implements the Scanner
interface so it can be used as a scan destination, similar to NullString.

func (*NullInt64) Scan

  1. func (n *NullInt64) Scan(value interface{}) error

Scan implements the Scanner interface.

func (NullInt64) Value

  1. func (n NullInt64) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type NullString

  1. type NullString struct {
  2. String string
  3. Valid bool // Valid is true if String is not NULL
  4. }

NullString represents a string that may be null. NullString implements the
Scanner interface so it can be used as a scan destination:

  1. var s NullString
  2. err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
  3. ...
  4. if s.Valid {
  5. // use s.String
  6. } else {
  7. // NULL value
  8. }

func (*NullString) Scan

  1. func (ns *NullString) Scan(value interface{}) error

Scan implements the Scanner interface.

func (NullString) Value

  1. func (ns NullString) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type Out

  1. type Out struct {
  2.  
  3. // Dest is a pointer to the value that will be set to the result of the
  4. // stored procedure's OUTPUT parameter.
  5. Dest interface{}
  6.  
  7. // In is whether the parameter is an INOUT parameter. If so, the input value to the stored
  8. // procedure is the dereferenced value of Dest's pointer, which is then replaced with
  9. // the output value.
  10. In bool
  11. // contains filtered or unexported fields
  12. }

Out may be used to retrieve OUTPUT value parameters from stored procedures.

Not all drivers and databases support OUTPUT value parameters.

Example usage:

  1. var outArg string
  2. _, err := db.ExecContext(ctx, "ProcName", sql.Named("Arg1", sql.Out{Dest: &outArg}))

type RawBytes

  1. type RawBytes []byte

RawBytes is a byte slice that holds a reference to memory owned by the database
itself. After a Scan into a RawBytes, the slice is only valid until the next
call to Next, Scan, or Close.

type Result

  1. type Result interface {
  2. // LastInsertId returns the integer generated by the database
  3. // in response to a command. Typically this will be from an
  4. // "auto increment" column when inserting a new row. Not all
  5. // databases support this feature, and the syntax of such
  6. // statements varies.
  7. LastInsertId() (int64, error)
  8.  
  9. // RowsAffected returns the number of rows affected by an
  10. // update, insert, or delete. Not every database or database
  11. // driver may support this.
  12. RowsAffected() (int64, error)
  13. }

A Result summarizes an executed SQL command.

type Row

  1. type Row struct {
  2. // contains filtered or unexported fields
  3. }

Row is the result of calling QueryRow to select a single row.

func (*Row) Scan

  1. func (r *Row) Scan(dest ...interface{}) error

Scan copies the columns from the matched row into the values pointed at by dest.
See the documentation on Rows.Scan for details. If more than one row matches the
query, Scan uses the first row and discards the rest. If no row matches the
query, Scan returns ErrNoRows.

type Rows

  1. type Rows struct {
  2. // contains filtered or unexported fields
  3. }

Rows is the result of a query. Its cursor starts before the first row of the
result set. Use Next to advance through the rows:

  1. rows, err := db.Query("SELECT ...")
  2. ...
  3. defer rows.Close()
  4. for rows.Next() {
  5. var id int
  6. var name string
  7. err = rows.Scan(&id, &name)
  8. ...
  9. }
  10. err = rows.Err() // get any error encountered during iteration
  11. ...

func (*Rows) Close

  1. func (rs *Rows) Close() error

Close closes the Rows, preventing further enumeration. If Next is called and
returns false and there are no further result sets, the Rows are closed
automatically and it will suffice to check the result of Err. Close is
idempotent and does not affect the result of Err.

func (*Rows) ColumnTypes

  1. func (rs *Rows) ColumnTypes() ([]*ColumnType, error)

ColumnTypes returns column information such as column type, length, and
nullable. Some information may not be available from some drivers.

func (*Rows) Columns

  1. func (rs *Rows) Columns() ([]string, error)

Columns returns the column names. Columns returns an error if the rows are
closed, or if the rows are from QueryRow and there was a deferred error.

func (*Rows) Err

  1. func (rs *Rows) Err() error

Err returns the error, if any, that was encountered during iteration. Err may be
called after an explicit or implicit Close.

func (*Rows) Next

  1. func (rs *Rows) Next() bool

Next prepares the next result row for reading with the Scan method. It returns
true on success, or false if there is no next result row or an error happened
while preparing it. Err should be consulted to distinguish between the two
cases.

Every call to Scan, even the first one, must be preceded by a call to Next.

func (*Rows) NextResultSet

  1. func (rs *Rows) NextResultSet() bool

NextResultSet prepares the next result set for reading. It returns true if there
is further result sets, or false if there is no further result set or if there
is an error advancing to it. The Err method should be consulted to distinguish
between the two cases.

After calling NextResultSet, the Next method should always be called before
scanning. If there are further result sets they may not have rows in the result
set.

func (*Rows) Scan

  1. func (rs *Rows) Scan(dest ...interface{}) error

Scan copies the columns in the current row into the values pointed at by dest.
The number of values in dest must be the same as the number of columns in Rows.

Scan converts columns read from the database into the following common Go types
and special types provided by the sql package:

  1. *string
  2. *[]byte
  3. *int, *int8, *int16, *int32, *int64
  4. *uint, *uint8, *uint16, *uint32, *uint64
  5. *bool
  6. *float32, *float64
  7. *interface{}
  8. *RawBytes
  9. any type implementing Scanner (see Scanner docs)

In the most simple case, if the type of the value from the source column is an
integer, bool or string type T and dest is of type *T, Scan simply assigns the
value through the pointer.

Scan also converts between string and numeric types, as long as no information
would be lost. While Scan stringifies all numbers scanned from numeric database
columns into string, scans into numeric types are checked for overflow. For
example, a float64 with value 300 or a string with value “300” can scan into a
uint16, but not into a uint8, though float64(255) or “255” can scan into a
uint8. One exception is that scans of some float64 numbers to strings may lose
information when stringifying. In general, scan floating point columns into
float64.

If a dest argument has type []byte, Scan saves in that argument a copy of the
corresponding data. The copy is owned by the caller and can be modified and held
indefinitely. The copy can be avoided by using an argument of type
RawBytes
instead; see the documentation for RawBytes for restrictions on its use.

If an argument has type interface{}, Scan copies the value provided by the
underlying driver without conversion. When scanning from a source value of type
[]byte to
interface{}, a copy of the slice is made and the caller owns the
result.

Source values of type time.Time may be scanned into values of type time.Time, interface{}, string, or []byte. When converting to the latter two,
time.Format3339Nano is used.

Source values of type bool may be scanned into types bool, interface{},
string, []byte, or *RawBytes.

For scanning into *bool, the source may be true, false, 1, 0, or string inputs
parseable by strconv.ParseBool.

type Scanner

  1. type Scanner interface {
  2. // Scan assigns a value from a database driver.
  3. //
  4. // The src value will be of one of the following types:
  5. //
  6. // int64
  7. // float64
  8. // bool
  9. // []byte
  10. // string
  11. // time.Time
  12. // nil - for NULL values
  13. //
  14. // An error should be returned if the value cannot be stored
  15. // without loss of information.
  16. Scan(src interface{}) error
  17. }

Scanner is an interface used by Scan.

type Stmt

  1. type Stmt struct {
  2. // contains filtered or unexported fields
  3. }

Stmt is a prepared statement. A Stmt is safe for concurrent use by multiple
goroutines.

func (*Stmt) Close

  1. func (s *Stmt) Close() error

Close closes the statement.

func (*Stmt) Exec

  1. func (s *Stmt) Exec(args ...interface{}) (Result, error)

Exec executes a prepared statement with the given arguments and returns a Result
summarizing the effect of the statement.

func (*Stmt) ExecContext

  1. func (s *Stmt) ExecContext(ctx context.Context, args ...interface{}) (Result, error)

ExecContext executes a prepared statement with the given arguments and returns a
Result summarizing the effect of the statement.

func (*Stmt) Query

  1. func (s *Stmt) Query(args ...interface{}) (*Rows, error)

Query executes a prepared query statement with the given arguments and returns
the query results as a *Rows.

func (*Stmt) QueryContext

  1. func (s *Stmt) QueryContext(ctx context.Context, args ...interface{}) (*Rows, error)

QueryContext executes a prepared query statement with the given arguments and
returns the query results as a *Rows.

func (*Stmt) QueryRow

  1. func (s *Stmt) QueryRow(args ...interface{}) *Row

QueryRow executes a prepared query statement with the given arguments. If an
error occurs during the execution of the statement, that error will be returned
by a call to Scan on the returned Row, which is always non-nil. If the query
selects no rows, the
Row’s Scan will return ErrNoRows. Otherwise, the *Row’s
Scan scans the first selected row and discards the rest.

Example usage:

  1. var name string
  2. err := nameByUseridStmt.QueryRow(id).Scan(&name)

func (*Stmt) QueryRowContext

  1. func (s *Stmt) QueryRowContext(ctx context.Context, args ...interface{}) *Row

QueryRowContext executes a prepared query statement with the given arguments. If
an error occurs during the execution of the statement, that error will be
returned by a call to Scan on the returned Row, which is always non-nil. If the
query selects no rows, the
Row’s Scan will return ErrNoRows. Otherwise, the
*Row’s Scan scans the first selected row and discards the rest.

Example usage:

  1. var name string
  2. err := nameByUseridStmt.QueryRowContext(ctx, id).Scan(&name)

type Tx

  1. type Tx struct {
  2. // contains filtered or unexported fields
  3. }

Tx is an in-progress database transaction.

A transaction must end with a call to Commit or Rollback.

After a call to Commit or Rollback, all operations on the transaction fail with
ErrTxDone.

The statements prepared for a transaction by calling the transaction’s Prepare
or Stmt methods are closed by the call to Commit or Rollback.

func (*Tx) Commit

  1. func (tx *Tx) Commit() error

Commit commits the transaction.

func (*Tx) Exec

  1. func (tx *Tx) Exec(query string, args ...interface{}) (Result, error)

Exec executes a query that doesn’t return rows. For example: an INSERT and
UPDATE.

func (*Tx) ExecContext

  1. func (tx *Tx) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error)

ExecContext executes a query that doesn’t return rows. For example: an INSERT
and UPDATE.

func (*Tx) Prepare

  1. func (tx *Tx) Prepare(query string) (*Stmt, error)

Prepare creates a prepared statement for use within a transaction.

The returned statement operates within the transaction and can no longer be used
once the transaction has been committed or rolled back.

To use an existing prepared statement on this transaction, see Tx.Stmt.

func (*Tx) PrepareContext

  1. func (tx *Tx) PrepareContext(ctx context.Context, query string) (*Stmt, error)

PrepareContext creates a prepared statement for use within a transaction.

The returned statement operates within the transaction and will be closed when
the transaction has been committed or rolled back.

To use an existing prepared statement on this transaction, see Tx.Stmt.

The provided context will be used for the preparation of the context, not for
the execution of the returned statement. The returned statement will run in the
transaction context.

func (*Tx) Query

  1. func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error)

Query executes a query that returns rows, typically a SELECT.

func (*Tx) QueryContext

  1. func (tx *Tx) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)

QueryContext executes a query that returns rows, typically a SELECT.

func (*Tx) QueryRow

  1. func (tx *Tx) QueryRow(query string, args ...interface{}) *Row

QueryRow executes a query that is expected to return at most one row. QueryRow
always returns a non-nil value. Errors are deferred until Row’s Scan method is
called. If the query selects no rows, the Row’s Scan will return ErrNoRows.
Otherwise, the
Row’s Scan scans the first selected row and discards the rest.

func (*Tx) QueryRowContext

  1. func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row

QueryRowContext executes a query that is expected to return at most one row.
QueryRowContext always returns a non-nil value. Errors are deferred until Row’s
Scan method is called. If the query selects no rows, the Row’s Scan will return
ErrNoRows. Otherwise, the
Row’s Scan scans the first selected row and discards
the rest.

func (*Tx) Rollback

  1. func (tx *Tx) Rollback() error

Rollback aborts the transaction.

func (*Tx) Stmt

  1. func (tx *Tx) Stmt(stmt *Stmt) *Stmt

Stmt returns a transaction-specific prepared statement from an existing
statement.

Example:

  1. updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
  2. ...
  3. tx, err := db.Begin()
  4. ...
  5. res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)

The returned statement operates within the transaction and will be closed when
the transaction has been committed or rolled back.

func (*Tx) StmtContext

  1. func (tx *Tx) StmtContext(ctx context.Context, stmt *Stmt) *Stmt

StmtContext returns a transaction-specific prepared statement from an existing
statement.

Example:

  1. updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
  2. ...
  3. tx, err := db.Begin()
  4. ...
  5. res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203)

The provided context is used for the preparation of the statement, not for the
execution of the statement.

The returned statement operates within the transaction and will be closed when
the transaction has been committed or rolled back.

type TxOptions

  1. type TxOptions struct {
  2. // Isolation is the transaction isolation level.
  3. // If zero, the driver or database's default level is used.
  4. Isolation IsolationLevel
  5. ReadOnly bool
  6. }

TxOptions holds the transaction options to be used in DB.BeginTx.

Subdirectories