Package driver

import "database/sql/driver"
Overview
Index

Overview ▾

程序包驱动程序定义了由程序包sql使用的数据库驱动程序要实现的接口.

大多数代码应使用包sql.

Variables

Bool是一个ValueConverter,它将输入值转换为bool.

转换规则为:

- booleans are returned unchanged
- for integer types,
     1 is true
     0 is false,
     other integers are an error
- for strings and []byte, same rules as strconv.ParseBool
- all other types are an error
var Bool boolType

DefaultParameterConverter是ValueConverter的默认实现,在Stmt不实现ColumnConverter时使用.

如果IsValue(arg),则DefaultParameterConverter直接返回其参数. 否则,如果参数实现Valuer,则使用其Value方法返回Value. 作为备用,使用提供的参数的基础类型将其转换为Value:基础整数类型转换为int64,将其浮点数转换为float64,bool,string和[] byte. 如果参数是nil指针,则ConvertValue返回nil值. 如果参数是非null指针,则将其取消引用并递归调用ConvertValue. 其他类型是错误.

var DefaultParameterConverter defaultConverter

驱动程序应返回ErrBadConn以向sql程序包发出信号,告知驱动程序.conn处于错误状态(例如服务器已更早关闭了连接),并且sql程序包应在新连接上重试.

为防止重复操作,如果数据库服务器可能已经执行了该操作,则不应返回ErrBadConn. 即使服务器发回错误,也不应返回ErrBadConn.

var ErrBadConn = errors.New("driver: bad connection")

可以从NamedValueChecker返回ErrRemoveArgument,以指示sql程序包不要将参数传递给驱动程序查询接口. 接受不是SQL查询参数的查询特定选项或结构时,返回.

var ErrRemoveArgument = errors.New("driver: remove argument from query")

某些可选接口的方法可能返回ErrSkip,以在运行时指示快速路径不可用,并且sql包应继续执行,就像未实现可选接口一样. 仅在明确记录的地方支持ErrSkip.

var ErrSkip = errors.New("driver: skip fast-path; continue as if unimplemented")

Int32是一个ValueConverter,它将输入值转换为int64,并遵守int32值的限制.

var Int32 int32Type

ResultNoRows is a pre-defined Result for drivers to return when a DDL command (such as a CREATE TABLE) succeeds. It returns an error for both LastInsertId and RowsAffected.

var ResultNoRows noRows

字符串是一个ValueConverter,它将其输入转换为字符串. 如果该值已经是字符串或[] byte,则保持不变. 如果该值是其他类型,则使用fmt.Sprintf("%v",v)转换为字符串.

var String stringType

func IsScanValue

func IsScanValue(v interface{}) bool

IsScanValue等效于IsValue. 存在它是为了兼容性.

func IsValue

func IsValue(v interface{}) bool

IsValue报告v是否是有效的Value参数类型.

type ColumnConverter

如果语句知道其自己列的类型并且可以从任何类型转换为驱动程序Value,则可以由Stmt选择性地实现ColumnConverter.

不推荐使用:驱动程序应实现NamedValueChecker.

type ColumnConverter interface {
    // ColumnConverter returns a ValueConverter for the provided
    // column index. If the type of a specific column isn't known
    // or shouldn't be handled specially, DefaultValueConverter
    // can be returned.
    ColumnConverter(idx int) ValueConverter
}

type Conn

Conn是到数据库的连接. 多个goroutine不能同时使用它.

Conn被假定为有状态的.

type Conn interface {
    // Prepare returns a prepared statement, bound to this connection.
    Prepare(query string) (Stmt, error)

    // Close invalidates and potentially stops any current
    // prepared statements and transactions, marking this
    // connection as no longer in use.
    //
    // Because the sql package maintains a free pool of
    // connections and only calls Close when there's a surplus of
    // idle connections, it shouldn't be necessary for drivers to
    // do their own connection caching.
    Close() error

    // Begin starts and returns a new transaction.
    //
    // Deprecated: Drivers should implement ConnBeginTx instead (or additionally).
    Begin() (Tx, error)
}

type ConnBeginTx 1.8

ConnBeginTx使用上下文和TxOptions增强了Conn接口.

type ConnBeginTx interface {
    // BeginTx starts and returns a new transaction.
    // If the context is canceled by the user the sql package will
    // call Tx.Rollback before discarding and closing the connection.
    //
    // This must check opts.Isolation to determine if there is a set
    // isolation level. If the driver does not support a non-default
    // level and one is set or if there is a non-default isolation level
    // that is not supported, an error must be returned.
    //
    // This must also check opts.ReadOnly to determine if the read-only
    // value is true to either set the read-only transaction property if supported
    // or return an error if it is not supported.
    BeginTx(ctx context.Context, opts TxOptions) (Tx, error)
}

type ConnPrepareContext 1.8

ConnPrepareContext使用上下文增强了Conn接口.

type ConnPrepareContext interface {
    // PrepareContext returns a prepared statement, bound to this connection.
    // context is for the preparation of the statement,
    // it must not store the context within the statement itself.
    PrepareContext(ctx context.Context, query string) (Stmt, error)
}

type Connector 1.10

连接器代表固定配置的驱动程序,可以创建任意数量的等效Conns供多个goroutine使用.

可以将连接器传递给sql.OpenDB,以允许驱动程序实现自己的sql.DB构造函数,或由DriverContext的OpenConnector方法返回,以允许驱动程序访问上下文并避免重复分析驱动程序配置.

type Connector interface {
    // Connect returns a connection to the database.
    // Connect may return a cached connection (one previously
    // closed), but doing so is unnecessary; the sql package
    // maintains a pool of idle connections for efficient re-use.
    //
    // The provided context.Context is for dialing purposes only
    // (see net.DialContext) and should not be stored or used for
    // other purposes.
    //
    // The returned connection is only used by one goroutine at a
    // time.
    Connect(context.Context) (Conn, error)

    // Driver returns the underlying Driver of the Connector,
    // mainly to maintain compatibility with the Driver method
    // on sql.DB.
    Driver() Driver
}

type Driver

驱动程序是必须由数据库驱动程序实现的接口.

数据库驱动程序可以实现DriverContext来访问上下文,并且对于连接池仅解析一次名称,而不是对每个连接解析一次.

type Driver interface {
    // Open returns a new connection to the database.
    // The name is a string in a driver-specific format.
    //
    // Open may return a cached connection (one previously
    // closed), but doing so is unnecessary; the sql package
    // maintains a pool of idle connections for efficient re-use.
    //
    // The returned connection is only used by one goroutine at a
    // time.
    Open(name string) (Conn, error)
}

type DriverContext 1.10

如果驱动程序实现了DriverContext,则sql.DB将调用OpenConnector以获得连接器,然后调用该连接器的Conn方法以获取每个所需的连接,而不是为每个连接调用驱动程序的Open方法. 两步序列允许驱动程序仅解析一次名称,还提供对每个Conn上下文的访问.

type DriverContext interface {
    // OpenConnector must parse the name in the same format that Driver.Open
    // parses the name parameter.
    OpenConnector(name string) (Connector, error)
}

type Execer

Execer是可以由Conn实现的可选接口.

如果Conn既未实现ExecerContext也未实现Execer,则sql包的DB.Exec将首先准备查询,执行该语句,然后关闭该语句.

执行可能会返回ErrSkip.

不推荐使用:驱动程序应改为实现ExecerContext.

type Execer interface {
    Exec(query string, args []Value) (Result, error)
}

type ExecerContext 1.8

ExecerContext是可以由Conn实现的可选接口.

如果Conn没有实现ExecerContext,则sql包的DB.Exec将退回到Execer;否则,将返回到Execer. 如果Conn也未实现Execer,则DB.Exec将首先准备查询,执行该语句,然后关闭该语句.

ExecerContext可能返回ErrSkip.

ExecerContext必须遵守上下文超时并在取消上下文时返回.

type ExecerContext interface {
    ExecContext(ctx context.Context, query string, args []NamedValue) (Result, error)
}

type IsolationLevel 1.8

IsolationLevel是存储在TxOptions中的事务隔离级别.

应该将这种类型与sql.IsolationLevel以及在其上定义的任何值都视为相同.

type IsolationLevel int

type NamedValue 1.8

NamedValue包含值名称和值.

type NamedValue struct {
    // If the Name is not empty it should be used for the parameter identifier and
    // not the ordinal position.
    //
    // Name will not have a symbol prefix.
    Name string

    // Ordinal position of the parameter starting from one and is always set.
    Ordinal int

    // Value is the parameter value.
    Value Value
}

type NamedValueChecker 1.9

NamedValueChecker可以选择由Conn或Stmt实现. 它为驱动程序提供了更多控制权,以处理Go和数据库类型超出允许的默认值类型.

sql包将按以下顺序检查值检查器,并在找到的第一个匹配项处停止:Stmt.NamedValueChecker,Conn.NamedValueChecker,Stmt.ColumnConverter,DefaultParameterConverter.

如果CheckNamedValue返回ErrRemoveArgument,则NamedValue将不包括在最终查询参数中. 这可以用于将特殊选项传递给查询本身.

如果返回ErrSkip,则将列转换器错误检查路径用作参数. 驾驶员在精疲力尽自己的特殊情况后,不妨返回ErrSkip.

type NamedValueChecker interface {
    // CheckNamedValue is called before passing arguments to the driver
    // and is called in place of any ColumnConverter. CheckNamedValue must do type
    // validation and conversion as appropriate for the driver.
    CheckNamedValue(*NamedValue) error
}

type NotNull

NotNull是一种通过不允许nil值但以其他方式委托给另一个ValueConverter来实现ValueConverter的类型.

type NotNull struct {
    Converter ValueConverter
}

func (NotNull) ConvertValue

func (n NotNull) ConvertValue(v interface{}) (Value, error)

type Null

Null是一种类型,它通过允许nil值来实现ValueConverter,但通过委派给另一个ValueConverter来实现.

type Null struct {
    Converter ValueConverter
}

func (Null) ConvertValue

func (n Null) ConvertValue(v interface{}) (Value, error)

type Pinger 1.8

Pinger是可由Conn实现的可选接口.

如果Conn没有实现Pinger,则sql包的DB.Ping和DB.PingContext将检查是否至少有一个Conn可用.

如果Conn.Ping返回ErrBadConn,则DB.Ping和DB.PingContext将从池中删除Conn.

type Pinger interface {
    Ping(ctx context.Context) error
}

type Queryer 1.1

查询器是可以由Conn实现的可选接口.

如果Conn既未实现QueryerContext也未实现Queryer,则sql包的DB.Query将首先准备查询,执行该语句,然后关闭该语句.

查询可能返回ErrSkip.

不推荐使用:驱动程序应改为实现QueryerContext.

type Queryer interface {
    Query(query string, args []Value) (Rows, error)
}

type QueryerContext 1.8

QueryerContext是可以由Conn实现的可选接口.

如果Conn没有实现QueryerContext,则sql包的DB.Query将退回到Queryer;否则,将返回到Queryer. 如果Conn也未实现Queryer,则DB.Query将首先准备查询,执行该语句,然后关闭该语句.

QueryerContext可能返回ErrSkip.

QueryerContext必须遵守上下文超时并在取消上下文时返回.

type QueryerContext interface {
    QueryContext(ctx context.Context, query string, args []NamedValue) (Rows, error)
}

type Result

结果是查询执行的结果.

type Result interface {
    // LastInsertId returns the database's auto-generated ID
    // after, for example, an INSERT into a table with primary
    // key.
    LastInsertId() (int64, error)

    // RowsAffected returns the number of rows affected by the
    // query.
    RowsAffected() (int64, error)
}

type Rows

行是对已执行查询的结果进行迭代的迭代器.

type Rows interface {
    // Columns returns the names of the columns. The number of
    // columns of the result is inferred from the length of the
    // slice. If a particular column name isn't known, an empty
    // string should be returned for that entry.
    Columns() []string

    // Close closes the rows iterator.
    Close() error

    // Next is called to populate the next row of data into
    // the provided slice. The provided slice will be the same
    // size as the Columns() are wide.
    //
    // Next should return io.EOF when there are no more rows.
    //
    // The dest should not be written to outside of Next. Care
    // should be taken when closing Rows not to modify
    // a buffer held in dest.
    Next(dest []Value) error
}

type RowsAffected

RowsAffected实现INSERT或UPDATE操作的Result,该操作会使许多行发生突变.

type RowsAffected int64

func (RowsAffected) LastInsertId

func (RowsAffected) LastInsertId() (int64, error)

func (RowsAffected) RowsAffected

func (v RowsAffected) RowsAffected() (int64, error)

type RowsColumnTypeDatabaseTypeName 1.8

RowsColumnTypeDatabaseTypeName可以由Rows实现. 它应返回不带长度的数据库系统类型名称. 类型名称应为大写. 返回类型的示例:" VARCHAR"," NVARCHAR"," VARCHAR2"," CHAR"," TEXT"," DECIMAL"," SMALLINT"," INT"," BIGINT"," BOOL"," [] BIGINT" ," JSONB"," XML"," TIMESTAMP".

type RowsColumnTypeDatabaseTypeName interface {
    Rows
    ColumnTypeDatabaseTypeName(index int) string
}

type RowsColumnTypeLength 1.8

RowsColumnTypeLength可以由Rows实现. 如果列是可变长度类型,则应返回列类型的长度. 如果该列不是可变长度类型,则ok应该返回false. 如果长度不受系统限制的限制,则应返回math.MaxInt64. 以下是各种类型的返回值的示例:

TEXT          (math.MaxInt64, true)
varchar(10)   (10, true)
nvarchar(10)  (10, true)
decimal       (0, false)
int           (0, false)
bytea(30)     (30, true)
type RowsColumnTypeLength interface {
    Rows
    ColumnTypeLength(index int) (length int64, ok bool)
}

type RowsColumnTypeNullable 1.8

RowsColumnTypeNullable可以由Rows实现. 如果知道该列可以为空,则可为空的值应为true;如果已知该列不可为空,则应为false. 如果列的可空性未知,则ok应该为false.

type RowsColumnTypeNullable interface {
    Rows
    ColumnTypeNullable(index int) (nullable, ok bool)
}

type RowsColumnTypePrecisionScale 1.8

RowsColumnTypePrecisionScale可以由Rows实现. 它应返回十进制类型的精度和小数位数. 如果不适用,确定应该为假. 以下是各种类型的返回值的示例:

decimal(38, 4)    (38, 4, true)
int               (0, 0, false)
decimal           (math.MaxInt64, math.MaxInt64, true)
type RowsColumnTypePrecisionScale interface {
    Rows
    ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool)
}

type RowsColumnTypeScanType 1.8

RowsColumnTypeScanType可以由Rows实现. 它应该返回可用于扫描类型的值类型. 例如,数据库列类型" bigint"应返回" reflect.TypeOf(int64(0))".

type RowsColumnTypeScanType interface {
    Rows
    ColumnTypeScanType(index int) reflect.Type
}

type RowsNextResultSet 1.8

RowsNextResultSet通过提供一种信号通知驱动程序前进到下一个结果集,从而扩展了Rows接口.

type RowsNextResultSet interface {
    Rows

    // HasNextResultSet is called at the end of the current result set and
    // reports whether there is another result set after the current one.
    HasNextResultSet() bool

    // NextResultSet advances the driver to the next result set even
    // if there are remaining rows in the current result set.
    //
    // NextResultSet should return io.EOF when there are no more result sets.
    NextResultSet() error
}

type SessionResetter 1.10

SessionResetter可以由Conn实现,以允许驱动程序重置与连接关联的会话状态并发出错误的连接信号.

type SessionResetter interface {
    // ResetSession is called while a connection is in the connection
    // pool. No queries will run on this connection until this method returns.
    //
    // If the connection is bad this should return driver.ErrBadConn to prevent
    // the connection from being returned to the connection pool. Any other
    // error will be discarded.
    ResetSession(ctx context.Context) error
}

type Stmt

Stmt是一个准备好的语句. 它绑定到Conn,并且不能同时被多个goroutine使用.

type Stmt interface {
    // Close closes the statement.
    //
    // As of Go 1.1, a Stmt will not be closed if it's in use
    // by any queries.
    Close() error

    // NumInput returns the number of placeholder parameters.
    //
    // If NumInput returns >= 0, the sql package will sanity check
    // argument counts from callers and return errors to the caller
    // before the statement's Exec or Query methods are called.
    //
    // NumInput may also return -1, if the driver doesn't know
    // its number of placeholders. In that case, the sql package
    // will not sanity check Exec or Query argument counts.
    NumInput() int

    // Exec executes a query that doesn't return rows, such
    // as an INSERT or UPDATE.
    //
    // Deprecated: Drivers should implement StmtExecContext instead (or additionally).
    Exec(args []Value) (Result, error)

    // Query executes a query that may return rows, such as a
    // SELECT.
    //
    // Deprecated: Drivers should implement StmtQueryContext instead (or additionally).
    Query(args []Value) (Rows, error)
}

type StmtExecContext 1.8

StmtExecContext通过为Exec提供上下文来增强Stmt接口.

type StmtExecContext interface {
    // ExecContext executes a query that doesn't return rows, such
    // as an INSERT or UPDATE.
    //
    // ExecContext must honor the context timeout and return when it is canceled.
    ExecContext(ctx context.Context, args []NamedValue) (Result, error)
}

type StmtQueryContext 1.8

StmtQueryContext通过为Query提供上下文来增强Stmt接口.

type StmtQueryContext interface {
    // QueryContext executes a query that may return rows, such as a
    // SELECT.
    //
    // QueryContext must honor the context timeout and return when it is canceled.
    QueryContext(ctx context.Context, args []NamedValue) (Rows, error)
}

type Tx

Tx是一笔交易.

type Tx interface {
    Commit() error
    Rollback() error
}

type TxOptions 1.8

TxOptions保存事务选项.

此类型应被认为与sql.TxOptions相同.

type TxOptions struct {
    Isolation IsolationLevel
    ReadOnly  bool
}

type Value

值是驱动程序必须能够处理的值. 它可以是nil,由数据库驱动程序的NamedValueChecker接口处理的类型,或者是以下类型之一的实例:

int64
float64
bool
[]byte
string
time.Time

如果驱动程序支持游标,则返回的Value也可以在此包中实现Rows接口. 例如,当用户选择一个游标,例如"从双精度选择游标(从my_table中选择*)"时,将使用此功能. 如果关闭选择中的行,则游标行也将关闭.

type Value interface{}

type ValueConverter

ValueConverter是提供ConvertValue方法的接口.

驱动程序包提供了ValueConverter的各种实现,以提供驱动程序之间转换的一致实现. ValueConverters具有多种用途:

* converting from the Value types as provided by the sql package
  into a database table's specific column type and making sure it
  fits, such as making sure a particular int64 fits in a
  table's uint16 column.

* converting a value as given from the database into one of the
  driver Value types.

* by the sql package, for converting from a driver's Value type
  to a user's type in a scan.
type ValueConverter interface {
    // ConvertValue converts a value to a driver Value.
    ConvertValue(v interface{}) (Value, error)
}

type Valuer

Valuer是提供Value方法的接口.

实现Valuer接口的类型能够将自身转换为驱动程序Value.

type Valuer interface {
    // Value returns a driver Value.
    // Value must not panic.
    Value() (Value, error)
}

by  ICOPY.SITE