Movatterモバイル変換


[0]ホーム

URL:


sql

packagestandard library
go1.24.5Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 8, 2025 License:BSD-3-ClauseImports:18Imported by:186,125

Details

Repository

cs.opensource.google/go/go

Links

Documentation

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.Seehttps://golang.org/s/sqldrivers for a list of drivers.

Drivers that do not support context cancellation will not return untilafter the query is completed.

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

Example (OpenDBCLI)
package mainimport ("context""database/sql""flag""log""os""os/signal""time")var pool *sql.DB // Database connection pool.func main() {id := flag.Int64("id", 0, "person ID to find")dsn := flag.String("dsn", os.Getenv("DSN"), "connection data source name")flag.Parse()if len(*dsn) == 0 {log.Fatal("missing dsn flag")}if *id == 0 {log.Fatal("missing person ID")}var err error// Opening a driver typically will not attempt to connect to the database.pool, err = sql.Open("driver-name", *dsn)if err != nil {// This will not be a connection error, but a DSN parse error or// another initialization error.log.Fatal("unable to use data source name", err)}defer pool.Close()pool.SetConnMaxLifetime(0)pool.SetMaxIdleConns(3)pool.SetMaxOpenConns(3)ctx, stop := context.WithCancel(context.Background())defer stop()appSignal := make(chan os.Signal, 3)signal.Notify(appSignal, os.Interrupt)go func() {<-appSignalstop()}()Ping(ctx)Query(ctx, *id)}// Ping the database to verify DSN provided by the user is valid and the// server accessible. If the ping fails exit the program with an error.func Ping(ctx context.Context) {ctx, cancel := context.WithTimeout(ctx, 1*time.Second)defer cancel()if err := pool.PingContext(ctx); err != nil {log.Fatalf("unable to connect to database: %v", err)}}// Query the database for the information requested and prints the results.// If the query fails exit the program with an error.func Query(ctx context.Context, id int64) {ctx, cancel := context.WithTimeout(ctx, 5*time.Second)defer cancel()var name stringerr := pool.QueryRowContext(ctx, "select p.name from people as p where p.id = :id;", sql.Named("id", id)).Scan(&name)if err != nil {log.Fatal("unable to execute search query", err)}log.Println("name=", name)}

Example (OpenDBService)
package mainimport ("context""database/sql""encoding/json""fmt""io""log""net/http""time")func main() {// Opening a driver typically will not attempt to connect to the database.db, err := sql.Open("driver-name", "database=test1")if err != nil {// This will not be a connection error, but a DSN parse error or// another initialization error.log.Fatal(err)}db.SetConnMaxLifetime(0)db.SetMaxIdleConns(50)db.SetMaxOpenConns(50)s := &Service{db: db}http.ListenAndServe(":8080", s)}type Service struct {db *sql.DB}func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {db := s.dbswitch r.URL.Path {default:http.Error(w, "not found", http.StatusNotFound)returncase "/healthz":ctx, cancel := context.WithTimeout(r.Context(), 1*time.Second)defer cancel()err := s.db.PingContext(ctx)if err != nil {http.Error(w, fmt.Sprintf("db down: %v", err), http.StatusFailedDependency)return}w.WriteHeader(http.StatusOK)returncase "/quick-action":// This is a short SELECT. Use the request context as the base of// the context timeout.ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)defer cancel()id := 5org := 10var name stringerr := db.QueryRowContext(ctx, `selectp.namefrompeople as pjoin organization as o on p.organization = o.idwherep.id = :idand o.id = :org;`,sql.Named("id", id),sql.Named("org", org),).Scan(&name)if err != nil {if err == sql.ErrNoRows {http.Error(w, "not found", http.StatusNotFound)return}http.Error(w, err.Error(), http.StatusInternalServerError)return}io.WriteString(w, name)returncase "/long-action":// This is a long SELECT. Use the request context as the base of// the context timeout, but give it some time to finish. If// the client cancels before the query is done the query will also// be canceled.ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)defer cancel()var names []stringrows, err := db.QueryContext(ctx, "select p.name from people as p where p.active = true;")if err != nil {http.Error(w, err.Error(), http.StatusInternalServerError)return}for rows.Next() {var name stringerr = rows.Scan(&name)if err != nil {break}names = append(names, name)}// Check for errors during rows "Close".// This may be more important if multiple statements are executed// in a single batch and rows were written as well as read.if closeErr := rows.Close(); closeErr != nil {http.Error(w, closeErr.Error(), http.StatusInternalServerError)return}// Check for row scan error.if err != nil {http.Error(w, err.Error(), http.StatusInternalServerError)return}// Check for errors during row iteration.if err = rows.Err(); err != nil {http.Error(w, err.Error(), http.StatusInternalServerError)return}json.NewEncoder(w).Encode(names)returncase "/async-action":// This action has side effects that we want to preserve// even if the client cancels the HTTP request part way through.// For this we do not use the http request context as a base for// the timeout.ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()var orderRef = "ABC123"tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})if err != nil {http.Error(w, err.Error(), http.StatusInternalServerError)return}_, err = tx.ExecContext(ctx, "stored_proc_name", orderRef)if err != nil {tx.Rollback()http.Error(w, err.Error(), http.StatusInternalServerError)return}err = tx.Commit()if err != nil {http.Error(w, "action in unknown state, check state before attempting again", http.StatusInternalServerError)return}w.WriteHeader(http.StatusOK)return}}

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrConnDone =errors.New("sql: connection is already closed")

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

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

ErrNoRows is returned byRow.Scan whenDB.QueryRow doesn't return arow. In such a case, QueryRow returns a placeholder*Row value thatdefers this error until a Scan.

View Source
var ErrTxDone =errors.New("sql: transaction has already been committed or rolled back")

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

Functions

funcDriversadded ingo1.4

func Drivers() []string

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

funcRegister

func Register(namestring, driverdriver.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.

Types

typeColumnTypeadded ingo1.8

type ColumnType struct {// contains filtered or unexported fields}

ColumnType contains the name and type of a column.

func (*ColumnType)DatabaseTypeNameadded ingo1.8

func (ci *ColumnType) DatabaseTypeName()string

DatabaseTypeName returns the database system name of the column type. If an emptystring is returned, then the driver type name is not supported.Consult your driver documentation for a list of driver data types.ColumnType.Length specifiersare not included.Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL","INT", and "BIGINT".

func (*ColumnType)DecimalSizeadded ingo1.8

func (ci *ColumnType) DecimalSize() (precision, scaleint64, okbool)

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

func (*ColumnType)Lengthadded ingo1.8

func (ci *ColumnType) Length() (lengthint64, okbool)

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

func (*ColumnType)Nameadded ingo1.8

func (ci *ColumnType) Name()string

Name returns the name or alias of the column.

func (*ColumnType)Nullableadded ingo1.8

func (ci *ColumnType) Nullable() (nullable, okbool)

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

func (*ColumnType)ScanTypeadded ingo1.8

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

ScanType returns a Go type suitable for scanning into usingRows.Scan.If a driver does not support this property ScanType will returnthe type of an empty interface.

typeConnadded ingo1.9

type Conn struct {// contains filtered or unexported fields}

Conn represents a single database connection rather than a pool of databaseconnections. Prefer running queries fromDB unless there is a specificneed for a continuous single database connection.

A Conn must callConn.Close to return the connection to the database pooland may do so concurrently with a running query.

After a call toConn.Close, all operations on theconnection fail withErrConnDone.

func (*Conn)BeginTxadded ingo1.9

func (c *Conn) BeginTx(ctxcontext.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 backthe transaction.Tx.Commit will return an error if the context provided toBeginTx is canceled.

The providedTxOptions 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)Closeadded ingo1.9

func (c *Conn) Close()error

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

func (*Conn)ExecContextadded ingo1.9

func (c *Conn) ExecContext(ctxcontext.Context, querystring, args ...any) (Result,error)

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

Example
package mainimport ("context""database/sql""log")var (ctx context.Contextdb  *sql.DB)func main() {// A *DB is a pool of connections. Call Conn to reserve a connection for// exclusive use.conn, err := db.Conn(ctx)if err != nil {log.Fatal(err)}defer conn.Close() // Return the connection to the pool.id := 41result, err := conn.ExecContext(ctx, `UPDATE balances SET balance = balance + 10 WHERE user_id = ?;`, id)if err != nil {log.Fatal(err)}rows, err := result.RowsAffected()if err != nil {log.Fatal(err)}if rows != 1 {log.Fatalf("expected single row affected, got %d rows affected", rows)}}

func (*Conn)PingContextadded ingo1.9

func (c *Conn) PingContext(ctxcontext.Context)error

PingContext verifies the connection to the database is still alive.

func (*Conn)PrepareContextadded ingo1.9

func (c *Conn) PrepareContext(ctxcontext.Context, querystring) (*Stmt,error)

PrepareContext creates a prepared statement for later queries or executions.Multiple queries or executions may be run concurrently from thereturned statement.The caller must call the statement's*Stmt.Close methodwhen the statement is no longer needed.

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

func (*Conn)QueryContextadded ingo1.9

func (c *Conn) QueryContext(ctxcontext.Context, querystring, args ...any) (*Rows,error)

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

func (*Conn)QueryRowContextadded ingo1.9

func (c *Conn) QueryRowContext(ctxcontext.Context, querystring, args ...any) *Row

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

func (*Conn)Rawadded ingo1.13

func (c *Conn) Raw(f func(driverConnany)error) (errerror)

Raw executes f exposing the underlying driver connection for theduration of f. The driverConn must not be used outside of f.

Once f returns and err is notdriver.ErrBadConn, theConn will continue to be usableuntilConn.Close is called.

typeDB

type DB struct {// contains filtered or unexported fields}

DB is a database handle representing a pool of zero or moreunderlying connections. It's safe for concurrent use by multiplegoroutines.

The sql package creates and frees connections automatically; italso maintains a free pool of idle connections. If the database hasa concept of per-connection state, such state can be reliably observedwithin a transaction (Tx) or connection (Conn). OnceDB.Begin is called, thereturnedTx is bound to a single connection. OnceTx.Commit orTx.Rollback is called on the transaction, that transaction'sconnection is returned toDB's idle connection pool. The pool sizecan be controlled withDB.SetMaxIdleConns.

funcOpen

func Open(driverName, dataSourceNamestring) (*DB,error)

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

Most users will open a database via a driver-specific connectionhelper function that returns a*DB. No database drivers are includedin the Go standard library. Seehttps://golang.org/s/sqldrivers fora list of third-party drivers.

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

The returnedDB is safe for concurrent use by multiple goroutinesand maintains its own pool of idle connections. Thus, the Openfunction should be called just once. It is rarely necessary toclose aDB.

funcOpenDBadded ingo1.10

func OpenDB(cdriver.Connector) *DB

OpenDB opens a database using adriver.Connector, allowing drivers tobypass a string based data source name.

Most users will open a database via a driver-specific connectionhelper function that returns a*DB. No database drivers are includedin the Go standard library. Seehttps://golang.org/s/sqldrivers fora list of third-party drivers.

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

The returnedDB is safe for concurrent use by multiple goroutinesand maintains its own pool of idle connections. Thus, the OpenDBfunction should be called just once. It is rarely necessary toclose aDB.

func (*DB)Begin

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

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

Begin usescontext.Background internally; to specify the context, useDB.BeginTx.

func (*DB)BeginTxadded ingo1.8

func (db *DB) BeginTx(ctxcontext.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 backthe transaction.Tx.Commit will return an error if the context provided toBeginTx is canceled.

The providedTxOptions 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.

Example
package mainimport ("context""database/sql""log")var (ctx context.Contextdb  *sql.DB)func main() {tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})if err != nil {log.Fatal(err)}id := 37_, execErr := tx.Exec(`UPDATE users SET status = ? WHERE id = ?`, "paid", id)if execErr != nil {_ = tx.Rollback()log.Fatal(execErr)}if err := tx.Commit(); err != nil {log.Fatal(err)}}

func (*DB)Close

func (db *DB) Close()error

Close closes the database and prevents new queries from starting.Close then waits for all queries that have started processing on the serverto finish.

It is rare to Close aDB, as theDB handle is meant to belong-lived and shared between many goroutines.

func (*DB)Connadded ingo1.9

func (db *DB) Conn(ctxcontext.Context) (*Conn,error)

Conn returns a single connection by either opening a new connectionor returning an existing connection from the connection pool. Conn willblock 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 bycallingConn.Close.

func (*DB)Driver

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

Driver returns the database's underlying driver.

func (*DB)Exec

func (db *DB) Exec(querystring, args ...any) (Result,error)

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

Exec usescontext.Background internally; to specify the context, useDB.ExecContext.

func (*DB)ExecContextadded ingo1.8

func (db *DB) ExecContext(ctxcontext.Context, querystring, args ...any) (Result,error)

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

Example
package mainimport ("context""database/sql""log")var (ctx context.Contextdb  *sql.DB)func main() {id := 47result, err := db.ExecContext(ctx, "UPDATE balances SET balance = balance + 10 WHERE user_id = ?", id)if err != nil {log.Fatal(err)}rows, err := result.RowsAffected()if err != nil {log.Fatal(err)}if rows != 1 {log.Fatalf("expected to affect 1 row, affected %d", rows)}}

func (*DB)Pingadded ingo1.1

func (db *DB) Ping()error

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

Ping usescontext.Background internally; to specify the context, useDB.PingContext.

func (*DB)PingContextadded ingo1.8

func (db *DB) PingContext(ctxcontext.Context)error

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

Example
package mainimport ("context""database/sql""log""time")var (ctx context.Contextdb  *sql.DB)func main() {// Ping and PingContext may be used to determine if communication with// the database server is still possible.//// When used in a command line application Ping may be used to establish// that further queries are possible; that the provided DSN is valid.//// When used in long running service Ping may be part of the health// checking system.ctx, cancel := context.WithTimeout(ctx, 1*time.Second)defer cancel()status := "up"if err := db.PingContext(ctx); err != nil {status = "down"}log.Println(status)}

func (*DB)Prepare

func (db *DB) Prepare(querystring) (*Stmt,error)

Prepare creates a prepared statement for later queries or executions.Multiple queries or executions may be run concurrently from thereturned statement.The caller must call the statement's*Stmt.Close methodwhen the statement is no longer needed.

Prepare usescontext.Background internally; to specify the context, useDB.PrepareContext.

Example
package mainimport ("context""database/sql""log")var db *sql.DBfunc main() {projects := []struct {mascot  stringrelease int}{{"tux", 1991},{"duke", 1996},{"gopher", 2009},{"moby dock", 2013},}stmt, err := db.Prepare("INSERT INTO projects(id, mascot, release, category) VALUES( ?, ?, ?, ? )")if err != nil {log.Fatal(err)}defer stmt.Close() // Prepared statements take up server resources and should be closed after use.for id, project := range projects {if _, err := stmt.Exec(id+1, project.mascot, project.release, "open source"); err != nil {log.Fatal(err)}}}

func (*DB)PrepareContextadded ingo1.8

func (db *DB) PrepareContext(ctxcontext.Context, querystring) (*Stmt,error)

PrepareContext creates a prepared statement for later queries or executions.Multiple queries or executions may be run concurrently from thereturned statement.The caller must call the statement's*Stmt.Close methodwhen the statement is no longer needed.

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

func (*DB)Query

func (db *DB) Query(querystring, args ...any) (*Rows,error)

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

Query usescontext.Background internally; to specify the context, useDB.QueryContext.

Example (MultipleResultSets)
package mainimport ("context""database/sql""log")var db *sql.DBfunc main() {age := 27q := `create temp table uid (id bigint); -- Create temp table for queries.insert into uidselect id from users where age < ?; -- Populate temp table.-- First result set.selectusers.id, namefromusersjoin uid on users.id = uid.id;-- Second result set.select ur.user, ur.rolefromuser_roles as urjoin uid on uid.id = ur.user;`rows, err := db.Query(q, age)if err != nil {log.Fatal(err)}defer rows.Close()for rows.Next() {var (id   int64name string)if err := rows.Scan(&id, &name); err != nil {log.Fatal(err)}log.Printf("id %d name is %s\n", id, name)}if !rows.NextResultSet() {log.Fatalf("expected more result sets: %v", rows.Err())}var roleMap = map[int64]string{1: "user",2: "admin",3: "gopher",}for rows.Next() {var (id   int64role int64)if err := rows.Scan(&id, &role); err != nil {log.Fatal(err)}log.Printf("id %d has role %s\n", id, roleMap[role])}if err := rows.Err(); err != nil {log.Fatal(err)}}

func (*DB)QueryContextadded ingo1.8

func (db *DB) QueryContext(ctxcontext.Context, querystring, args ...any) (*Rows,error)

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

Example
package mainimport ("context""database/sql""fmt""log""strings")var (ctx context.Contextdb  *sql.DB)func main() {age := 27rows, err := db.QueryContext(ctx, "SELECT name FROM users WHERE age=?", age)if err != nil {log.Fatal(err)}defer rows.Close()names := make([]string, 0)for rows.Next() {var name stringif err := rows.Scan(&name); err != nil {// Check for a scan error.// Query rows will be closed with defer.log.Fatal(err)}names = append(names, name)}// If the database is being written to ensure to check for Close// errors that may be returned from the driver. The query may// encounter an auto-commit error and be forced to rollback changes.rerr := rows.Close()if rerr != nil {log.Fatal(rerr)}// Rows.Err will report the last error encountered by Rows.Scan.if err := rows.Err(); err != nil {log.Fatal(err)}fmt.Printf("%s are %d years old", strings.Join(names, ", "), age)}

func (*DB)QueryRow

func (db *DB) QueryRow(querystring, args ...any) *Row

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

QueryRow usescontext.Background internally; to specify the context, useDB.QueryRowContext.

func (*DB)QueryRowContextadded ingo1.8

func (db *DB) QueryRowContext(ctxcontext.Context, querystring, args ...any) *Row

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

Example
package mainimport ("context""database/sql""log""time")var (ctx context.Contextdb  *sql.DB)func main() {id := 123var username stringvar created time.Timeerr := db.QueryRowContext(ctx, "SELECT username, created_at FROM users WHERE id=?", id).Scan(&username, &created)switch {case err == sql.ErrNoRows:log.Printf("no user with id %d\n", id)case err != nil:log.Fatalf("query error: %v\n", err)default:log.Printf("username is %q, account created on %s\n", username, created)}}

func (*DB)SetConnMaxIdleTimeadded ingo1.15

func (db *DB) SetConnMaxIdleTime(dtime.Duration)

SetConnMaxIdleTime sets the maximum amount of time a connection may be idle.

Expired connections may be closed lazily before reuse.

If d <= 0, connections are not closed due to a connection's idle time.

func (*DB)SetConnMaxLifetimeadded ingo1.6

func (db *DB) SetConnMaxLifetime(dtime.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 not closed due to a connection's age.

func (*DB)SetMaxIdleConnsadded ingo1.1

func (db *DB) SetMaxIdleConns(nint)

SetMaxIdleConns sets the maximum number of connections in the idleconnection 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.

The default max idle connections is currently 2. This may change ina future release.

func (*DB)SetMaxOpenConnsadded ingo1.2

func (db *DB) SetMaxOpenConns(nint)

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

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

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

func (*DB)Statsadded ingo1.5

func (db *DB) Stats()DBStats

Stats returns database statistics.

typeDBStatsadded ingo1.5

type DBStats struct {MaxOpenConnectionsint// Maximum number of open connections to the database.// Pool StatusOpenConnectionsint// The number of established connections both in use and idle.InUseint// The number of connections currently in use.Idleint// The number of idle connections.// CountersWaitCountint64// The total number of connections waited for.WaitDurationtime.Duration// The total time blocked waiting for a new connection.MaxIdleClosedint64// The total number of connections closed due to SetMaxIdleConns.MaxIdleTimeClosedint64// The total number of connections closed due to SetConnMaxIdleTime.MaxLifetimeClosedint64// The total number of connections closed due to SetConnMaxLifetime.}

DBStats contains database statistics.

typeIsolationLeveladded ingo1.8

type IsolationLevelint

IsolationLevel is the transaction isolation level used inTxOptions.

const (LevelDefaultIsolationLevel =iotaLevelReadUncommittedLevelReadCommittedLevelWriteCommittedLevelRepeatableReadLevelSnapshotLevelSerializableLevelLinearizable)

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

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

func (IsolationLevel)Stringadded ingo1.11

func (iIsolationLevel) String()string

String returns the name of the transaction isolation level.

typeNamedArgadded ingo1.8

type NamedArg struct {// Name is the name of the parameter placeholder.//// If empty, the ordinal position in the argument list will be// used.//// Name must omit any symbol prefix.Namestring// Value is the value of the parameter.// It may be assigned the same value types as the query// arguments.Valueany// contains filtered or unexported fields}

A NamedArg is a named argument. NamedArg values may be used asarguments toDB.Query orDB.Exec and bind to the corresponding namedparameter in the SQL statement.

For a more concise way to create NamedArg values, seetheNamed function.

funcNamedadded ingo1.8

func Named(namestring, valueany)NamedArg

Named provides a more concise way to createNamedArg values.

Example usage:

db.ExecContext(ctx, `    delete from Invoice    where        TimeCreated < @end        and TimeCreated >= @start;`,    sql.Named("start", startTime),    sql.Named("end", endTime),)

typeNulladded ingo1.22.0

type Null[Tany] struct {V     TValidbool}

Null represents a value that may be null.Null implements theScanner interface soit can be used as a scan destination:

var s Null[string]err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)...if s.Valid {   // use s.V} else {   // NULL value}

T should be one of the types accepted bydriver.Value.

func (*Null[T])Scanadded ingo1.22.0

func (n *Null[T]) Scan(valueany)error

func (Null[T])Valueadded ingo1.22.0

func (nNull[T]) Value() (driver.Value,error)

typeNullBool

type NullBool struct {BoolboolValidbool// Valid is true if Bool is not NULL}

NullBool represents a bool that may be null.NullBool implements theScanner interface soit can be used as a scan destination, similar toNullString.

func (*NullBool)Scan

func (n *NullBool) Scan(valueany)error

Scan implements theScanner interface.

func (NullBool)Value

func (nNullBool) Value() (driver.Value,error)

Value implements thedriver.Valuer interface.

typeNullByteadded ingo1.17

type NullByte struct {BytebyteValidbool// Valid is true if Byte is not NULL}

NullByte represents a byte that may be null.NullByte implements theScanner interface soit can be used as a scan destination, similar toNullString.

func (*NullByte)Scanadded ingo1.17

func (n *NullByte) Scan(valueany)error

Scan implements theScanner interface.

func (NullByte)Valueadded ingo1.17

func (nNullByte) Value() (driver.Value,error)

Value implements thedriver.Valuer interface.

typeNullFloat64

type NullFloat64 struct {Float64float64Validbool// Valid is true if Float64 is not NULL}

NullFloat64 represents a float64 that may be null.NullFloat64 implements theScanner interface soit can be used as a scan destination, similar toNullString.

func (*NullFloat64)Scan

func (n *NullFloat64) Scan(valueany)error

Scan implements theScanner interface.

func (NullFloat64)Value

func (nNullFloat64) Value() (driver.Value,error)

Value implements thedriver.Valuer interface.

typeNullInt16added ingo1.17

type NullInt16 struct {Int16int16Validbool// Valid is true if Int16 is not NULL}

NullInt16 represents an int16 that may be null.NullInt16 implements theScanner interface soit can be used as a scan destination, similar toNullString.

func (*NullInt16)Scanadded ingo1.17

func (n *NullInt16) Scan(valueany)error

Scan implements theScanner interface.

func (NullInt16)Valueadded ingo1.17

func (nNullInt16) Value() (driver.Value,error)

Value implements thedriver.Valuer interface.

typeNullInt32added ingo1.13

type NullInt32 struct {Int32int32Validbool// Valid is true if Int32 is not NULL}

NullInt32 represents an int32 that may be null.NullInt32 implements theScanner interface soit can be used as a scan destination, similar toNullString.

func (*NullInt32)Scanadded ingo1.13

func (n *NullInt32) Scan(valueany)error

Scan implements theScanner interface.

func (NullInt32)Valueadded ingo1.13

func (nNullInt32) Value() (driver.Value,error)

Value implements thedriver.Valuer interface.

typeNullInt64

type NullInt64 struct {Int64int64Validbool// Valid is true if Int64 is not NULL}

NullInt64 represents an int64 that may be null.NullInt64 implements theScanner interface soit can be used as a scan destination, similar toNullString.

func (*NullInt64)Scan

func (n *NullInt64) Scan(valueany)error

Scan implements theScanner interface.

func (NullInt64)Value

func (nNullInt64) Value() (driver.Value,error)

Value implements thedriver.Valuer interface.

typeNullString

type NullString struct {StringstringValidbool// Valid is true if String is not NULL}

NullString represents a string that may be null.NullString implements theScanner interface soit can be used as a scan destination:

var s NullStringerr := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)...if s.Valid {   // use s.String} else {   // NULL value}

func (*NullString)Scan

func (ns *NullString) Scan(valueany)error

Scan implements theScanner interface.

func (NullString)Value

func (nsNullString) Value() (driver.Value,error)

Value implements thedriver.Valuer interface.

typeNullTimeadded ingo1.13

type NullTime struct {Timetime.TimeValidbool// Valid is true if Time is not NULL}

NullTime represents atime.Time that may be null.NullTime implements theScanner interface soit can be used as a scan destination, similar toNullString.

func (*NullTime)Scanadded ingo1.13

func (n *NullTime) Scan(valueany)error

Scan implements theScanner interface.

func (NullTime)Valueadded ingo1.13

func (nNullTime) Value() (driver.Value,error)

Value implements thedriver.Valuer interface.

typeOutadded ingo1.9

type Out struct {// Dest is a pointer to the value that will be set to the result of the// stored procedure's OUTPUT parameter.Destany// In is whether the parameter is an INOUT parameter. If so, the input value to the stored// procedure is the dereferenced value of Dest's pointer, which is then replaced with// the output value.Inbool// contains filtered or unexported fields}

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

Not all drivers and databases support OUTPUT value parameters.

Example usage:

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

typeRawBytes

type RawBytes []byte

RawBytes is a byte slice that holds a reference to memory owned bythe database itself. After aRows.Scan into a RawBytes, the slice is onlyvalid until the next call toRows.Next,Rows.Scan, orRows.Close.

typeResult

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

A Result summarizes an executed SQL command.

typeRow

type Row struct {// contains filtered or unexported fields}

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

func (*Row)Erradded ingo1.15

func (r *Row) Err()error

Err provides a way for wrapping packages to check forquery errors without callingRow.Scan.Err returns the error, if any, that was encountered while running the query.If this error is not nil, this error will also be returned fromRow.Scan.

func (*Row)Scan

func (r *Row) Scan(dest ...any)error

Scan copies the columns from the matched row into the valuespointed at by dest. See the documentation onRows.Scan for details.If more than one row matches the query,Scan uses the first row and discards the rest. If no row matchesthe query, Scan returnsErrNoRows.

typeRows

type Rows struct {// contains filtered or unexported fields}

Rows is the result of a query. Its cursor starts before the first rowof the result set. UseRows.Next to advance from row to row.

Example
package mainimport ("context""database/sql""log""strings")var (ctx context.Contextdb  *sql.DB)func main() {age := 27rows, err := db.QueryContext(ctx, "SELECT name FROM users WHERE age=?", age)if err != nil {log.Fatal(err)}defer rows.Close()names := make([]string, 0)for rows.Next() {var name stringif err := rows.Scan(&name); err != nil {log.Fatal(err)}names = append(names, name)}// Check for errors from iterating over rows.if err := rows.Err(); err != nil {log.Fatal(err)}log.Printf("%s are %d years old", strings.Join(names, ", "), age)}

func (*Rows)Close

func (rs *Rows) Close()error

Close closes theRows, preventing further enumeration. IfRows.Next is calledand returns false and there are no further result sets,theRows are closed automatically and it will suffice to check theresult ofRows.Err. Close is idempotent and does not affect the result ofRows.Err.

func (*Rows)ColumnTypesadded ingo1.8

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

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

Columns returns the column names.Columns returns an error if the rows are closed.

func (*Rows)Err

func (rs *Rows) Err()error

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

func (*Rows)Next

func (rs *Rows) Next()bool

Next prepares the next result row for reading with theRows.Scan method. Itreturns true on success, or false if there is no next result row or an errorhappened while preparing it.Rows.Err should be consulted to distinguish betweenthe two cases.

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

func (*Rows)NextResultSetadded ingo1.8

func (rs *Rows) NextResultSet()bool

NextResultSet prepares the next result set for reading. It reports whetherthere is further result sets, or false if there is no further result setor if there is an error advancing to it. TheRows.Err method should be consultedto distinguish between the two cases.

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

func (*Rows)Scan

func (rs *Rows) Scan(dest ...any)error

Scan copies the columns in the current row into the values pointedat by dest. The number of values in dest must be the same as thenumber of columns inRows.

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

*string*[]byte*int, *int8, *int16, *int32, *int64*uint, *uint8, *uint16, *uint32, *uint64*bool*float32, *float64*interface{}*RawBytes*Rows (cursor value)any type implementing Scanner (see Scanner docs)

In the most simple case, if the type of the value from the sourcecolumn 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 noinformation would be lost. While Scan stringifies all numbersscanned from numeric database columns into *string, scans intonumeric types are checked for overflow. For example, a float64 withvalue 300 or a string with value "300" can scan into a uint16, butnot into a uint8, though float64(255) or "255" can scan into auint8. One exception is that scans of some float64 numbers tostrings may lose information when stringifying. In general, scanfloating point columns into *float64.

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

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

Source values of typetime.Time may be scanned into values of type*time.Time, *interface{}, *string, or *[]byte. When converting tothe latter two,time.RFC3339Nano 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, orstring inputs parseable bystrconv.ParseBool.

Scan can also convert a cursor returned from a query, such as"select cursor(select * from my_table) from dual", into a*Rows value that can itself be scanned from. The parentselect query will close any cursor*Rows if the parent*Rows is closed.

If any of the first arguments implementingScanner returns an error,that error will be wrapped in the returned error.

typeScanner

type Scanner interface {// Scan assigns a value from a database driver.//// The src value will be of one of the following types:////    int64//    float64//    bool//    []byte//    string//    time.Time//    nil - for NULL values//// An error should be returned if the value cannot be stored// without loss of information.//// Reference types such as []byte are only valid until the next call to Scan// and should not be retained. Their underlying memory is owned by the driver.// If retention is necessary, copy their values before the next call to Scan.Scan(srcany)error}

Scanner is an interface used byRows.Scan.

typeStmt

type Stmt struct {// contains filtered or unexported fields}

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

If a Stmt is prepared on aTx orConn, it will be bound to a singleunderlying connection forever. If theTx orConn closes, the Stmt willbecome unusable and all operations will return an error.If a Stmt is prepared on aDB, it will remain usable for the lifetime of theDB. When the Stmt needs to execute on a new underlying connection, it willprepare itself on the new connection automatically.

Example
package mainimport ("context""database/sql""log")var (ctx context.Contextdb  *sql.DB)func main() {// In normal use, create one Stmt when your process starts.stmt, err := db.PrepareContext(ctx, "SELECT username FROM users WHERE id = ?")if err != nil {log.Fatal(err)}defer stmt.Close()// Then reuse it each time you need to issue the query.id := 43var username stringerr = stmt.QueryRowContext(ctx, id).Scan(&username)switch {case err == sql.ErrNoRows:log.Fatalf("no user with id %d", id)case err != nil:log.Fatal(err)default:log.Printf("username is %s\n", username)}}

func (*Stmt)Close

func (s *Stmt) Close()error

Close closes the statement.

func (*Stmt)Exec

func (s *Stmt) Exec(args ...any) (Result,error)

Exec executes a prepared statement with the given arguments andreturns aResult summarizing the effect of the statement.

Exec usescontext.Background internally; to specify the context, useStmt.ExecContext.

func (*Stmt)ExecContextadded ingo1.8

func (s *Stmt) ExecContext(ctxcontext.Context, args ...any) (Result,error)

ExecContext executes a prepared statement with the given arguments andreturns aResult summarizing the effect of the statement.

func (*Stmt)Query

func (s *Stmt) Query(args ...any) (*Rows,error)

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

Query usescontext.Background internally; to specify the context, useStmt.QueryContext.

func (*Stmt)QueryContextadded ingo1.8

func (s *Stmt) QueryContext(ctxcontext.Context, args ...any) (*Rows,error)

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

func (*Stmt)QueryRow

func (s *Stmt) QueryRow(args ...any) *Row

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

Example usage:

var name stringerr := nameByUseridStmt.QueryRow(id).Scan(&name)

QueryRow usescontext.Background internally; to specify the context, useStmt.QueryRowContext.

func (*Stmt)QueryRowContextadded ingo1.8

func (s *Stmt) QueryRowContext(ctxcontext.Context, args ...any) *Row

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

Example
package mainimport ("context""database/sql""log")var (ctx context.Contextdb  *sql.DB)func main() {// In normal use, create one Stmt when your process starts.stmt, err := db.PrepareContext(ctx, "SELECT username FROM users WHERE id = ?")if err != nil {log.Fatal(err)}defer stmt.Close()// Then reuse it each time you need to issue the query.id := 43var username stringerr = stmt.QueryRowContext(ctx, id).Scan(&username)switch {case err == sql.ErrNoRows:log.Fatalf("no user with id %d", id)case err != nil:log.Fatal(err)default:log.Printf("username is %s\n", username)}}

typeTx

type Tx struct {// contains filtered or unexported fields}

Tx is an in-progress database transaction.

A transaction must end with a call toTx.Commit orTx.Rollback.

After a call toTx.Commit orTx.Rollback, all operations on thetransaction fail withErrTxDone.

The statements prepared for a transaction by callingthe transaction'sTx.Prepare orTx.Stmt methods are closedby the call toTx.Commit orTx.Rollback.

func (*Tx)Commit

func (tx *Tx) Commit()error

Commit commits the transaction.

func (*Tx)Exec

func (tx *Tx) Exec(querystring, args ...any) (Result,error)

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

Exec usescontext.Background internally; to specify the context, useTx.ExecContext.

func (*Tx)ExecContextadded ingo1.8

func (tx *Tx) ExecContext(ctxcontext.Context, querystring, args ...any) (Result,error)

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

Example
package mainimport ("context""database/sql""log")var (ctx context.Contextdb  *sql.DB)func main() {tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})if err != nil {log.Fatal(err)}id := 37_, execErr := tx.ExecContext(ctx, "UPDATE users SET status = ? WHERE id = ?", "paid", id)if execErr != nil {if rollbackErr := tx.Rollback(); rollbackErr != nil {log.Fatalf("update failed: %v, unable to rollback: %v\n", execErr, rollbackErr)}log.Fatalf("update failed: %v", execErr)}if err := tx.Commit(); err != nil {log.Fatal(err)}}

func (*Tx)Prepare

func (tx *Tx) Prepare(querystring) (*Stmt,error)

Prepare creates a prepared statement for use within a transaction.

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

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

Prepare usescontext.Background internally; to specify the context, useTx.PrepareContext.

Example
package mainimport ("context""database/sql""log")var db *sql.DBfunc main() {projects := []struct {mascot  stringrelease int}{{"tux", 1991},{"duke", 1996},{"gopher", 2009},{"moby dock", 2013},}tx, err := db.Begin()if err != nil {log.Fatal(err)}defer tx.Rollback() // The rollback will be ignored if the tx has been committed later in the function.stmt, err := tx.Prepare("INSERT INTO projects(id, mascot, release, category) VALUES( ?, ?, ?, ? )")if err != nil {log.Fatal(err)}defer stmt.Close() // Prepared statements take up server resources and should be closed after use.for id, project := range projects {if _, err := stmt.Exec(id+1, project.mascot, project.release, "open source"); err != nil {log.Fatal(err)}}if err := tx.Commit(); err != nil {log.Fatal(err)}}

func (*Tx)PrepareContextadded ingo1.8

func (tx *Tx) PrepareContext(ctxcontext.Context, querystring) (*Stmt,error)

PrepareContext creates a prepared statement for use within a transaction.

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

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

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

func (*Tx)Query

func (tx *Tx) Query(querystring, args ...any) (*Rows,error)

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

Query usescontext.Background internally; to specify the context, useTx.QueryContext.

func (*Tx)QueryContextadded ingo1.8

func (tx *Tx) QueryContext(ctxcontext.Context, querystring, args ...any) (*Rows,error)

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

func (*Tx)QueryRow

func (tx *Tx) QueryRow(querystring, args ...any) *Row

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

QueryRow usescontext.Background internally; to specify the context, useTx.QueryRowContext.

func (*Tx)QueryRowContextadded ingo1.8

func (tx *Tx) QueryRowContext(ctxcontext.Context, querystring, args ...any) *Row

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

func (*Tx)Rollback

func (tx *Tx) Rollback()error

Rollback aborts the transaction.

Example
package mainimport ("context""database/sql""log")var (ctx context.Contextdb  *sql.DB)func main() {tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})if err != nil {log.Fatal(err)}id := 53_, err = tx.ExecContext(ctx, "UPDATE drivers SET status = ? WHERE id = ?;", "assigned", id)if err != nil {if rollbackErr := tx.Rollback(); rollbackErr != nil {log.Fatalf("update drivers: unable to rollback: %v", rollbackErr)}log.Fatal(err)}_, err = tx.ExecContext(ctx, "UPDATE pickups SET driver_id = $1;", id)if err != nil {if rollbackErr := tx.Rollback(); rollbackErr != nil {log.Fatalf("update failed: %v, unable to back: %v", err, rollbackErr)}log.Fatal(err)}if err := tx.Commit(); err != nil {log.Fatal(err)}}

func (*Tx)Stmt

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

Stmt returns a transaction-specific prepared statement froman existing statement.

Example:

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

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

Stmt usescontext.Background internally; to specify the context, useTx.StmtContext.

func (*Tx)StmtContextadded ingo1.8

func (tx *Tx) StmtContext(ctxcontext.Context, stmt *Stmt) *Stmt

StmtContext returns a transaction-specific prepared statement froman existing statement.

Example:

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

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

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

typeTxOptionsadded ingo1.8

type TxOptions struct {// Isolation is the transaction isolation level.// If zero, the driver or database's default level is used.IsolationIsolationLevelReadOnlybool}

TxOptions holds the transaction options to be used inDB.BeginTx.

Source Files

View all Source files

Directories

PathSynopsis
Package driver defines interfaces to be implemented by database drivers as used by package sql.
Package driver defines interfaces to be implemented by database drivers as used by package sql.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp