go-mssqldb: github.com/denisenkom/go-mssqldb Index | Examples | Files | Directories

package mssql

import "github.com/denisenkom/go-mssqldb"

package mssql implements the TDS protocol used to connect to MS SQL Server (sqlserver) database servers.

This package registers the driver:

sqlserver: uses native "@" parameter placeholder names and does no pre-processing.

If the ordinal position is used for query parameters, identifiers will be named "@p1", "@p2", ... "@pN".

Please refer to the README for the format of the DSN. There are multiple DSN formats accepted: ADO style, ODBC style, and URL style. The following is an example of a URL style DSN:




Package Files

buf.go bulkcopy.go bulkcopy_sql.go convert.go decimal.go doc.go error.go log.go mssql.go mssql_go110.go mssql_go19.go net.go ntlm.go parser.go rpc.go tds.go token.go token_string.go tran.go tvp_go19.go types.go uniqueidentifier.go


var (
    ErrorEmptyTVPName        = errors.New("TVPTypeName must not be empty")
    ErrorTVPTypeSlice        = errors.New("TVPType must be slice type")
    ErrorTVPTypeSliceIsEmpty = errors.New("TVPType mustn't be null value")

func CopyIn Uses

func CopyIn(table string, options BulkOptions, columns ...string) string

func SetLogger Uses

func SetLogger(logger Logger)

type Bulk Uses

type Bulk struct {
    Options BulkOptions
    Debug   bool
    // contains filtered or unexported fields

func (*Bulk) AddRow Uses

func (b *Bulk) AddRow(row []interface{}) (err error)

AddRow immediately writes the row to the destination table. The arguments are the row values in the order they were specified.

func (*Bulk) Done Uses

func (b *Bulk) Done() (rowcount int64, err error)

type BulkOptions Uses

type BulkOptions struct {
    CheckConstraints  bool
    FireTriggers      bool
    KeepNulls         bool
    KilobytesPerBatch int
    RowsPerBatch      int
    Order             []string
    Tablock           bool

type Conn Uses

type Conn struct {
    // contains filtered or unexported fields

func (*Conn) Begin Uses

func (c *Conn) Begin() (driver.Tx, error)

func (*Conn) BeginTx Uses

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

BeginTx satisfies ConnBeginTx.

func (*Conn) CheckNamedValue Uses

func (c *Conn) CheckNamedValue(nv *driver.NamedValue) error

func (*Conn) Close Uses

func (c *Conn) Close() error

func (*Conn) Commit Uses

func (c *Conn) Commit() error

func (*Conn) CreateBulk Uses

func (cn *Conn) CreateBulk(table string, columns []string) (_ *Bulk)

func (*Conn) CreateBulkContext Uses

func (cn *Conn) CreateBulkContext(ctx context.Context, table string, columns []string) (_ *Bulk)

func (*Conn) Ping Uses

func (c *Conn) Ping(ctx context.Context) error

Ping is used to check if the remote server is available and satisfies the Pinger interface.

func (*Conn) Prepare Uses

func (c *Conn) Prepare(query string) (driver.Stmt, error)

func (*Conn) PrepareContext Uses

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

func (*Conn) ResetSession Uses

func (c *Conn) ResetSession(ctx context.Context) error

func (*Conn) Rollback Uses

func (c *Conn) Rollback() error

type Connector Uses

type Connector struct {

    // SessionInitSQL is executed after marking a given session to be reset.
    // When not present, the next query will still reset the session to the
    // database defaults.
    // When present the connection will immediately mark the session to
    // be reset, then execute the SessionInitSQL text to setup the session
    // that may be different from the base database defaults.
    // For Example, the application relies on the following defaults
    // but is not allowed to set them at the database system level.
    //    SET XACT_ABORT ON;
    //    SET TEXTSIZE -1;
    //    SET ANSI_NULLS ON;
    //    SET LOCK_TIMEOUT 10000;
    // SessionInitSQL should not attempt to manually call sp_reset_connection.
    // This will happen at the TDS layer.
    // SessionInitSQL is optional. The session will be reset even if
    // SessionInitSQL is empty.
    SessionInitSQL string

    // Dialer sets a custom dialer for all network operations.
    // If Dialer is not set, normal net dialers are used.
    Dialer Dialer
    // contains filtered or unexported fields

Connector holds the parsed DSN and is ready to make a new connection at any time.

In the future, settings that cannot be passed through a string DSN may be set directly on the connector.

func NewConnector Uses

func NewConnector(dsn string) (*Connector, error)

NewConnector creates a new connector from a DSN. The returned connector may be used with sql.OpenDB.

func (*Connector) Connect Uses

func (c *Connector) Connect(ctx context.Context) (driver.Conn, error)

Connect to the server and return a TDS connection.

func (*Connector) Driver Uses

func (c *Connector) Driver() driver.Driver

Driver underlying the Connector.

type DataValue Uses

type DataValue interface{}

type DateTime1 Uses

type DateTime1 time.Time

DateTime1 encodes parameters to original DateTime SQL types.

type DateTimeOffset Uses

type DateTimeOffset time.Time

DateTimeOffset encodes parameters to DateTimeOffset, preserving the UTC offset.

type Decimal Uses

type Decimal struct {
    // contains filtered or unexported fields


func Float64ToDecimal Uses

func Float64ToDecimal(f float64) (Decimal, error)

func Float64ToDecimalScale Uses

func Float64ToDecimalScale(f float64, scale uint8) (Decimal, error)

func (Decimal) BigInt Uses

func (d Decimal) BigInt() big.Int

func (Decimal) Bytes Uses

func (d Decimal) Bytes() []byte

func (Decimal) String Uses

func (d Decimal) String() string

func (Decimal) ToFloat64 Uses

func (d Decimal) ToFloat64() float64

func (Decimal) UnscaledBytes Uses

func (d Decimal) UnscaledBytes() []byte

type Dialer Uses

type Dialer interface {
    DialContext(ctx context.Context, network string, addr string) (net.Conn, error)

type Driver Uses

type Driver struct {
    // contains filtered or unexported fields

func (*Driver) Open Uses

func (d *Driver) Open(dsn string) (driver.Conn, error)

func (*Driver) OpenConnection Uses

func (d *Driver) OpenConnection(dsn string) (*Conn, error)

func (*Driver) OpenConnector Uses

func (d *Driver) OpenConnector(dsn string) (*Connector, error)

OpenConnector opens a new connector. Useful to dial with a context.

func (*Driver) SetLogger Uses

func (d *Driver) SetLogger(logger Logger)

type Error Uses

type Error struct {
    Number     int32
    State      uint8
    Class      uint8
    Message    string
    ServerName string
    ProcName   string
    LineNo     int32

Error represents an SQL Server error. This type includes methods for reading the contents of the struct, which allows calling programs to check for specific error conditions without having to import this package directly.


// call a function that might return a mssql error
err := callUsingMSSQL()

type ErrorWithNumber interface {
    SQLErrorNumber() int32

if errorWithNumber, ok := err.(ErrorWithNumber); ok {
    if errorWithNumber.SQLErrorNumber() == 1205 {
        fmt.Println("deadlock error")


// call a function that might return a mssql error
err := callUsingMSSQL()

type SQLError interface {
    SQLErrorNumber() int32
    SQLErrorMessage() string

if sqlError, ok := err.(SQLError); ok {
    if sqlError.SQLErrorNumber() == 1205 {
        fmt.Println("deadlock error", sqlError.SQLErrorMessage())

func (Error) Error Uses

func (e Error) Error() string

func (Error) SQLErrorClass Uses

func (e Error) SQLErrorClass() uint8

func (Error) SQLErrorLineNo Uses

func (e Error) SQLErrorLineNo() int32

func (Error) SQLErrorMessage Uses

func (e Error) SQLErrorMessage() string

func (Error) SQLErrorNumber Uses

func (e Error) SQLErrorNumber() int32

SQLErrorNumber returns the SQL Server error number.

func (Error) SQLErrorProcName Uses

func (e Error) SQLErrorProcName() string

func (Error) SQLErrorServerName Uses

func (e Error) SQLErrorServerName() string

func (Error) SQLErrorState Uses

func (e Error) SQLErrorState() uint8

type Logger Uses

type Logger interface {
    Printf(format string, v ...interface{})
    Println(v ...interface{})

type MssqlBulk Uses

type MssqlBulk = Bulk // Deprecated: users should transition to the new name when possible.

type MssqlBulkOptions Uses

type MssqlBulkOptions = BulkOptions // Deprecated: users should transition to the new name when possible.

type MssqlConn Uses

type MssqlConn = Conn // Deprecated: users should transition to the new name when possible.

type MssqlDriver Uses

type MssqlDriver = Driver // Deprecated: users should transition to the new name when possible.

type MssqlResult Uses

type MssqlResult = Result // Deprecated: users should transition to the new name when possible.

type MssqlRows Uses

type MssqlRows = Rows // Deprecated: users should transition to the new name when possible.

type MssqlStmt Uses

type MssqlStmt = Stmt // Deprecated: users should transition to the new name when possible.

type NVarCharMax Uses

type NVarCharMax string

type Result Uses

type Result struct {
    // contains filtered or unexported fields

func (*Result) LastInsertId Uses

func (r *Result) LastInsertId() (int64, error)

func (*Result) RowsAffected Uses

func (r *Result) RowsAffected() (int64, error)

type ReturnStatus Uses

type ReturnStatus int32

ReturnStatus may be used to return the return value from a proc.

var rs mssql.ReturnStatus
_, err := db.Exec("theproc", &rs)
log.Printf("return status = %d", rs)

type Rows Uses

type Rows struct {
    // contains filtered or unexported fields

func (*Rows) Close Uses

func (rc *Rows) Close() error

func (*Rows) ColumnTypeDatabaseTypeName Uses

func (r *Rows) ColumnTypeDatabaseTypeName(index int) string

RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return the database system type name without the length. Type names should be uppercase. Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", "CHAR", "TEXT", "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", "JSONB", "XML", "TIMESTAMP".

func (*Rows) ColumnTypeLength Uses

func (r *Rows) ColumnTypeLength(index int) (int64, bool)

RowsColumnTypeLength may be implemented by Rows. It should return the length of the column type if the column is a variable length type. If the column is not a variable length type ok should return false. If length is not limited other than system limits, it should return math.MaxInt64. The following are examples of returned values for various types:

TEXT          (math.MaxInt64, true)
varchar(10)   (10, true)
nvarchar(10)  (10, true)
decimal       (0, false)
int           (0, false)
bytea(30)     (30, true)

func (*Rows) ColumnTypeNullable Uses

func (r *Rows) ColumnTypeNullable(index int) (nullable, ok bool)

The nullable value should be true if it is known the column may be null, or false if the column is known to be not nullable. If the column nullability is unknown, ok should be false.

func (*Rows) ColumnTypePrecisionScale Uses

func (r *Rows) ColumnTypePrecisionScale(index int) (int64, int64, bool)

It should return the precision and scale for decimal types. If not applicable, ok should be false. The following are examples of returned values for various types:

decimal(38, 4)    (38, 4, true)
int               (0, 0, false)
decimal           (math.MaxInt64, math.MaxInt64, true)

func (*Rows) ColumnTypeScanType Uses

func (r *Rows) ColumnTypeScanType(index int) reflect.Type

It should return the value type that can be used to scan types into. For example, the database column type "bigint" this should return "reflect.TypeOf(int64(0))".

func (*Rows) Columns Uses

func (rc *Rows) Columns() (res []string)

func (*Rows) HasNextResultSet Uses

func (rc *Rows) HasNextResultSet() bool

func (*Rows) Next Uses

func (rc *Rows) Next(dest []driver.Value) error

func (*Rows) NextResultSet Uses

func (rc *Rows) NextResultSet() error

type Stmt Uses

type Stmt struct {
    // contains filtered or unexported fields

func (*Stmt) Close Uses

func (s *Stmt) Close() error

func (*Stmt) Exec Uses

func (s *Stmt) Exec(args []driver.Value) (driver.Result, error)

func (*Stmt) ExecContext Uses

func (s *Stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error)

func (*Stmt) NumInput Uses

func (s *Stmt) NumInput() int

func (*Stmt) Query Uses

func (s *Stmt) Query(args []driver.Value) (driver.Rows, error)

func (*Stmt) QueryContext Uses

func (s *Stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error)

func (*Stmt) SetQueryNotification Uses

func (s *Stmt) SetQueryNotification(id, options string, timeout time.Duration)

type StreamError Uses

type StreamError struct {
    Message string

func (StreamError) Error Uses

func (e StreamError) Error() string

type TVPType Uses

type TVPType struct {
    //TVP param name, mustn't be default value
    TVPTypeName string
    //TVP scheme name
    TVPScheme string
    //TVP Value. Param must be the slice, mustn't be nil
    TVPValue interface{}

TVPType is driver type, which allows supporting Table Valued Parameters (TVP) in SQL Server

type UniqueIdentifier Uses

type UniqueIdentifier [16]byte

func (*UniqueIdentifier) Scan Uses

func (u *UniqueIdentifier) Scan(v interface{}) error

func (UniqueIdentifier) String Uses

func (u UniqueIdentifier) String() string

func (UniqueIdentifier) Value Uses

func (u UniqueIdentifier) Value() (driver.Value, error)

type VarChar Uses

type VarChar string

VarChar parameter types.

type VarCharMax Uses

type VarCharMax string


batchbach splits a single script containing multiple batches separated by a keyword into multiple scripts.

Package mssql imports 33 packages (graph) and is imported by 279 packages. Updated 2019-02-04. Refresh now. Tools for package owners.