README
¶
Microsoft's official Go MSSQL driver
A pure Go database/sql driver for Microsoft SQL Server and Azure SQL Database. This is the recommended Go SQL Server driver for connecting Go applications to SQL Server, Azure SQL Database, Azure SQL Managed Instance, and Azure Synapse Analytics.
Keywords: golang sql server driver, go mssql, azure sql go, go-mssqldb, sql server golang, mssql go driver
Install
Requires Go 1.25 or above.
Install with go get github.com/microsoft/go-mssqldb@latest.
Connection Parameters and DSN
The recommended connection string uses a URL format:
sqlserver://username:password@host/instance?param1=value¶m2=value
Other supported formats are listed below.
All connection string parameters are case-insensitive. Providing the same parameter more than once with different casing (e.g., TrustServerCertificate and trustservercertificate) will result in a parse error.
Boolean parameters accept 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False, and additionally yes and no in any casing.
Common parameters
user id- enter the SQL Server Authentication user id or the Windows Authentication user id in the DOMAIN\User format. On Windows, if user id is empty or missing Single-Sign-On is used. The user domain sensitive to the case which is defined in the connection string.passworddatabaseconnection timeout- in seconds (default is 0 for no timeout), set to 0 for no timeout. Recommended to set to 0 and use context to manage query and connection timeouts.dial timeout- in seconds (default is 15 times the number of registered protocols), set to 0 for no timeout.encryptstrict- Data sent between client and server is encrypted E2E using TDS8.disable- Data send between client and server is not encrypted.false/optional/no/0/f- Data sent between client and server is not encrypted beyond the login packet. (Default)true/mandatory/yes/1/t- Data sent between client and server is encrypted.
app name- The application name (default is go-mssqldb)authenticator- Can be used to specify use of a registered authentication provider. (e.g. ntlm, winsspi (on windows) or krb5 (on linux))timezone- Sets the time zone used by the driver when parsing time types. For example:timezone=Asia/Shanghai. Supports IANA time zone names.
Connection parameters for ODBC and ADO style connection strings
server- host or host\instance (default localhost)port- specifies the host\instance port (default 1433). If instance name is provided but no port, the driver will use SQL Server Browser to discover the port.
Less common parameters
keepAlive- in seconds; 0 to disable (default is 30)failoverpartner- host or host\instance (default is no partner).failoverport- used only when there is no instance in failoverpartner (default 1433)failoverpartnerspn- The kerberos SPN (Service Principal Name) for the failover partner. Default is MSSQLSvc/host:(port|instance), matching how the driver generatesServerSPN.packet size- in bytes; 512 to 32767 (default is 4096)- Encrypted connections have a maximum packet size of 16383 bytes
- Further information on usage: https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/configure-the-network-packet-size-server-configuration-option
log- logging flags (default0/no logging,255for full logging)1log errors2log messages4log rows affected8trace sql statements16log statement parameters32log transaction begin/end64additional debug logs128log retries
TrustServerCertificate- false - Server certificate is checked. Default is false if encrypt is specified.
- true - Server certificate is not checked. Default is true if encrypt is not specified. If trust server certificate is true, driver accepts any certificate presented by the server and any host name in that certificate. In this mode, TLS is susceptible to man-in-the-middle attacks. This should be used only for testing.
certificate- The file path to a certificate authority (CA) certificate or server certificate for traditional X.509 chain validation. The specified certificate overrides the go platform specific CA certificates. The driver validates the certificate chain, expiry, and hostname. Supports PEM and DER formats.serverCertificate- The file path to a server certificate for byte-for-byte comparison validation (new in v1.9.6). The driver validates that the server's certificate exactly matches this file, skipping chain validation, expiry checks, and hostname validation. This matches Microsoft.Data.SqlClient behavior. Cannot be used withcertificateorhostnameincertificate. Supports PEM and DER formats.hostNameInCertificate- Specifies the Common Name (CN) in the server certificate. Default value is the server host. Used with thecertificateparameter, not applicable forserverCertificate.tlsmin- Specifies the minimum TLS version for negotiating encryption with the server. Recognized values are1.0,1.1,1.2,1.3. If not set to a recognized value the default value for thetlspackage will be used. The default is currently1.2.ServerSPN- The kerberos SPN (Service Principal Name) for the server. Default is MSSQLSvc/host:port.Workstation ID- The workstation name (default is the host name)ApplicationIntent- Can be given the valueReadOnlyto initiate a read-only connection to an Availability Group listener. Thedatabasemust be specified when connecting withApplication Intentset toReadOnly.protocol- forces use of a protocol. Make sure the corresponding package is imported.columnencryptionorcolumn encryption setting- a boolean value indicating whether Always Encrypted should be enabled on the connection.multisubnetfailovertrue(Default) Client attempt to connect to all IPs simultaneously.falseClient attempts to connect to IPs in serial.
guid conversion- Enables the conversion of GUIDs, so that byte order is preserved. UniqueIdentifier isn't supported for nullable fields, NullUniqueIdentifier must be used instead.
Connection parameters for namedpipe package
pipe- If set, no Browser query is made and named pipe used will be\\<host>\pipe\<pipe>protocolcan be set tonp- For a non-URL DSN, the
serverparameter can be set to the full pipe name like\\host\pipe\sql\query
If no pipe name can be derived from the DSN, connection attempts will first query the SQL Browser service to find the pipe name for the instance.
DNS Resolution through a Custom Dialer
Custom Dialers can be used to resolve DNS if the Connection's Dialer implements the HostDialer interface. This is helpful when the dialer is proxying requests to a different, private network and the DNS record is local to the private network.
Protocol configuration
To force a specific protocol for the connection there two several options:
- Prepend the server name in a DSN with the protocol and a colon, like
np:hostorlpc:hostortcp:host - Set the
protocolparameter to the protocol name
msdsn.ProtocolParsers can be reordered to prioritize other protocols ahead of tcp
The admin protocol will not be used for dialing unless the connection string explicitly specifies it. Note SQL Server allows only 1 admin (or DAC) connection to be active at a time.
Kerberos Active Directory authentication outside Windows
To connect with kerberos authentication from a Linux server you can use the optional krb5 package. Imported krb alongside the main driver
package main
import (
...
_ "github.com/microsoft/go-mssqldb"
_ "github.com/microsoft/go-mssqldb/integratedauth/krb5"
)
func main() {
...
}
It will become available for use when the connection string parameter "authenticator=krb5" is used.
The package supports authentication via 3 methods.
-
Keytabs - Specify the username, keytab file, the krb5.conf file, and realm.
authenticator=krb5;server=DatabaseServerName;database=DBName;user id=MyUserName;krb5-realm=domain.com;krb5-configfile=/etc/krb5.conf;krb5-keytabfile=~/MyUserName.keytab -
Credential Cache - Specify the krb5.conf file path and credential cache file path.
authenticator=krb5;server=DatabaseServerName;database=DBName;krb5-configfile=/etc/krb5.conf;krb5-credcachefile=~/MyUserNameCachedCreds -
Raw credentials - Specity krb5.confg, Username, Password and Realm.
authenticator=krb5;server=DatabaseServerName;database=DBName;user id=MyUserName;password=foo;krb5-realm=comani.com;krb5-configfile=/etc/krb5.conf;
Kerberos Parameters
authenticator- set this tokrb5to enable kerberos authentication. If this is not present, the default provider would bentlmfor unix andwinsspifor windows.krb5-configfile(optional) - path to kerberos configuration file. Defaults to/etc/krb5.conf. Can also be set usingKRB5_CONFIGenvironment variable.krb5-realm(required with keytab and raw credentials) - Domain name for kerberos authentication. Omit this parameter if the realm is part of the user name likeusername@REALM.krb5-keytabfile- path to Keytab file. Can also be set using environment variableKRB5_KTNAME. If no parameter or environment variable is set, theDefaultClientKeytabNamevalue from the krb5 config file is used.krb5-credcachefile- path to Credential cache. Can also be set using environment variableKRBCCNAME.krb5-dnslookupkdc- Optional parameter in all contexts. Set to lookup KDCs in DNS. Boolean. Default is true.krb5-udppreferencelimit- Optional parameter in all contexts. 1 means to always use tcp. MIT krb5 has a default value of 1465, and it prevents user setting more than 32700. Integer. Default is 1.
For further information on usage:
- https://web.mit.edu/kerberos/krb5-1.12/doc/admin/conf_files/krb5_conf.html
- https://web.mit.edu/kerberos/krb5-1.12/doc/basic/index.html
The connection string can be specified in one of three formats
-
URL: with
sqlserverscheme. username and password appears before the host. Any instance appears as the first segment in the path. All other options are query parameters. Examples:sqlserver://username:password@host/instance?param1=value¶m2=valuesqlserver://username:password@host:port?param1=value¶m2=valuesqlserver://sa@localhost/SQLExpress?database=master&connection+timeout=30// `SQLExpress instance.sqlserver://sa:mypass@localhost?database=master&connection+timeout=30// username=sa, password=mypass.sqlserver://sa:mypass@localhost:1234?database=master&connection+timeout=30// port 1234 on localhost.sqlserver://sa:my%7Bpass@somehost?connection+timeout=30// password is "my{pass" A string of this format can be constructed using theURLtype in thenet/urlpackage.
query := url.Values{} query.Add("app name", "MyAppName") u := &url.URL{ Scheme: "sqlserver", User: url.UserPassword(username, password), Host: fmt.Sprintf("%s:%d", hostname, port), // Path: instance, // if connecting to an instance instead of a port RawQuery: query.Encode(), } db, err := sql.Open("sqlserver", u.String())
-
sqlserver://username@host/instance?krb5-configfile=path/to/file&krb5-credcachefile=/path/to/cachesqlserver://username@host/instance?krb5-configfile=path/to/file&krb5-realm=domain.com&krb5-keytabfile=/path/to/keytabfile
For URL connection strings, percent-encode special characters in the username or password. Windows authentication usernames use
%5Cfor the domain separator, for examplesqlserver://DOMAIN%5Cusername:password@host. In ADO and ODBC connection strings, use the literalDOMAIN\usernameform.
-
ADO:
key=valuepairs separated by;. Values can contain;and other special characters by enclosing them in double quotes. Leading and trailing whitespace is ignored. Examples:server=localhost\\SQLExpress;user id=sa;database=master;app name=MyAppNameserver=localhost;user id=sa;database=master;app name=MyAppNameserver=localhost;user id=sa;password="my;complex;password";database=master// Password with semicolonsserver=localhost;user id=sa;password="value with ""quotes"" inside";database=master// Escaped quotes using double quotesserver=localhost;user id=sa;database=master;app name=MyAppName;krb5-configfile=path/to/file;krb5-credcachefile=path/to/cache;authenticator=krb5server=localhost;user id=sa;database=master;app name=MyAppName;krb5-configfile=path/to/file;krb5-realm=domain.com;krb5-keytabfile=path/to/keytabfile;authenticator=krb5
ADO strings support synonyms for common connection parameters:
- server <= addr, address, network address, data source
- user id <= user, uid
- password <= pwd
- database <= initial catalog
- app name <= application name, app
- connection timeout <= connect timeout, timeout
- failoverpartner <= failover partner
- failoverpartnerspn <= failover partner spn
- applicationintent <= application intent
- trustservercertificate <= trust server certificate
- multisubnetfailover <= multi subnet failover
- hostnameincertificate <= host name in certificate
- serverspn <= server spn
- servercertificate <= server certificate
- workstation id <= wsid
- columnencryption <= column encryption setting
-
ODBC: Prefix with
odbc,key=valuepairs separated by;. Allow;by wrapping values in{}. Examples:odbc:server=localhost\\SQLExpress;user id=sa;database=master;app name=MyAppNameodbc:server=localhost;user id=sa;database=master;app name=MyAppNameodbc:server=localhost;user id=sa;password={foo;bar}// Value marked with{}, password is "foo;bar"odbc:server=localhost;user id=sa;password={foo{bar}// Value marked with{}, password is "foo{bar"odbc:server=localhost;user id=sa;password={foobar }// Value marked with{}, password is "foobar "odbc:server=localhost;user id=sa;password=foo{bar// Literal{, password is "foo{bar"odbc:server=localhost;user id=sa;password=foo}bar// Literal}, password is "foo}bar"odbc:server=localhost;user id=sa;password={foo{bar}// Literal{, password is "foo{bar"odbc:server=localhost;user id=sa;password={foo}}bar}// Escaped} with}}`, password is "foo}bar"odbc:server=localhost;user id=sa;database=master;app name=MyAppName;krb5-configfile=path/to/file;krb5-credcachefile=path/to/cache;authenticator=krb5odbc:server=localhost;user id=sa;database=master;app name=MyAppName;krb5-configfile=path/to/file;krb5-realm=domain.com;krb5-keytabfile=path/to/keytabfile;authenticator=krb5
Using server certificates with encryption
The driver supports two ways to validate server certificates:
1. serverCertificate - Byte-for-byte certificate comparison (New in v1.9.6)
When you provide a serverCertificate parameter, the driver validates the server by comparing the certificate bytes exactly with the provided file. This:
- Skips hostname validation (allows mismatched hostnames)
- Skips certificate chain validation and expiry checks
- Only accepts connections where the server's certificate exactly matches the provided file
- Matches the behavior of Microsoft.Data.SqlClient
This is useful when:
- The server's DNS name doesn't match the certificate CN/SAN
- You want to validate against a specific certificate without hostname validation
- You're connecting through proxies or load balancers with different hostnames
Restrictions: serverCertificate cannot be used with certificate or hostnameincertificate parameters.
2. certificate - Traditional chain validation (Backward compatible)
The certificate parameter performs standard X.509 certificate chain validation:
- Validates the certificate chain against the provided CA certificate(s)
- Checks certificate expiry and validity
- Enforces hostname validation (unless
hostnameincertificateis used)
Obtaining the server certificate
You can obtain a copy of the server's certificate using OpenSSL:
openssl s_client -connect server:1433 -showcerts </dev/null 2>/dev/null | openssl x509 -outform PEM > cert.pem
Example connection strings
Using serverCertificate for byte-comparison (skips hostname validation):
URL format:
sqlserver://username:password@host:1433?database=master&encrypt=true&serverCertificate=/path/to/cert.pem
ADO format:
server=myserver;user id=sa;password=mypass;database=master;encrypt=true;serverCertificate=/path/to/cert.pem
Using certificate for traditional chain validation:
URL format:
sqlserver://username:password@host:1433?database=master&encrypt=true&certificate=/path/to/ca.pem
ADO format:
server=myserver;user id=sa;password=mypass;database=master;encrypt=true;certificate=/path/to/ca.pem
Azure Active Directory authentication
Azure Active Directory authentication uses temporary authentication tokens to authenticate.
The mssql package does not provide an implementation to obtain tokens: instead, import the azuread package and use driver name azuresql. This driver uses azidentity to acquire tokens using a variety of credential types.
To reduce friction in local development, ActiveDirectoryDefault can authenticate as the user signed into the Azure CLI.
Run the following command to sign into the Azure CLI before running your application using the ActiveDirectoryDefault connection string parameter:
az login
Azure CLI authentication isn't recommended for applications running in Azure. More details are available via the Azure authentication with the Azure Identity module for Go tutorial.
The credential type is determined by the new fedauth connection string parameter.
fedauth=ActiveDirectoryServicePrincipalorfedauth=ActiveDirectoryApplication- authenticates using an Azure Active Directory application client ID and client secret or certificate. Implemented using ClientSecretCredential or CertificateCredentialclientcertpath=<path to certificate file>;password=<certificate password>orpassword=<client secret>user id=<application id>[@tenantid]Note the@tenantidcomponent can be omitted if the server's tenant is the same as the application's tenant.
fedauth=ActiveDirectoryPassword- authenticates using a user name and password.user id=username@domainpassword=<password>applicationclientid=<application id>- This guid identifies an Azure Active Directory enterprise application that the AAD admin has approved for accessing Azure SQL database resources in the tenant. This driver does not have an associated application id of its own.
fedauth=ActiveDirectoryDefault- authenticates using a chained set of credentials. The chain is built from EnvironmentCredential -> ManagedIdentityCredential->AzureCLICredential. See DefaultAzureCredential docs for instructions on setting up your host environment to use it. Using this option allows you to have the same connection string in a service deployment as on your interactive development machine.fedauth=ActiveDirectoryManagedIdentityorfedauth=ActiveDirectoryMSI- authenticates using a system-assigned or user-assigned Azure Managed Identity.user id=<identity id>- optional id of user-assigned managed identity. If empty, system-assigned managed identity is used.resource id=<resource id>- optional resource id of user-assigned managed identity. If empty, system-assigned managed identity or user id are used (if both user id and resource id are provided, resource id will be used)
fedauth=ActiveDirectoryInteractive- authenticates using credentials acquired from an external web browser. Only suitable for use with human interaction.applicationclientid=<application id>- This guid identifies an Azure Active Directory enterprise application that the AAD admin has approved for accessing Azure SQL database resources in the tenant. This driver does not have an associated application id of its own.
fedauth=ActiveDirectoryDeviceCode- prints a message to stdout giving the user a URL and code to authenticate. Connection continues after user completes the login separately.fedauth=ActiveDirectoryAzCli- reuses local authentication the user already performed using Azure CLI.fedauth=ActiveDirectoryAzureDeveloperCli- reuses local authentication the user already performed using Azure Developer CLI.fedauth=ActiveDirectoryEnvironment- authenticates using environment variables. Uses the same environment variables as EnvironmentCredential.fedauth=ActiveDirectoryWorkloadIdentity- authenticates using workload identity credentials for Kubernetes and other OIDC environments.fedauth=ActiveDirectoryAzurePipelines- authenticates using Azure Pipelines service connection.user id=<service principal id>[@tenantid]- The service principal client ID and tenant ID. If not provided, usesAZURESUBSCRIPTION_CLIENT_IDandAZURESUBSCRIPTION_TENANT_IDenvironment variables.serviceconnectionid=<connection id>- The service connection ID from Azure DevOps. If not provided, usesAZURESUBSCRIPTION_SERVICE_CONNECTION_IDenvironment variable.systemtoken=<system token>- The system access token for the pipeline. If not provided, usesSYSTEM_ACCESSTOKENenvironment variable.- Note: Environment variables are automatically configured by Azure Pipelines in AzureCLI@2 and AzurePowerShell@5 tasks.
fedauth=ActiveDirectoryClientAssertion- authenticates using a client assertion (JWT token).user id=<client id>[@tenantid]- The client ID and tenant ID.clientassertion=<jwt token>- The JWT assertion token.
fedauth=ActiveDirectoryOnBehalfOf- authenticates using the on-behalf-of flow for delegated access.user id=<client id>[@tenantid]- The client ID and tenant ID.userassertion=<user token>- The user assertion token.- Use one of the following for client authentication:
password=<client secret>- Client secretclientcertpath=<path to certificate file>;password=<certificate password>- Client certificateclientassertion=<jwt token>- Client assertion JWT
Common Credential Options
The following connection string parameters can be used with most Azure credential types to provide additional configuration:
additionallyallowedtenants=<tenant1,tenant2>- Comma or semicolon-separated list of additional tenant IDs that the credential may authenticate to. Use "*" to allow any tenant.disableinstancediscovery=true- Disables Microsoft Entra instance discovery. Set totrueonly for disconnected or private clouds like Azure Stack.tokenfilepath=<path>- ForActiveDirectoryWorkloadIdentity, specifies the path to the Kubernetes service account token file.sendcertificatechain=true- For certificate-based authentication, controls whether to send the full certificate chain in token requests. Required for Subject Name/Issuer (SNI) authentication.
import (
"database/sql"
"net/url"
// Import the Azure AD driver module (also imports the regular driver package)
"github.com/microsoft/go-mssqldb/azuread"
)
func ConnectWithMSI() (*sql.DB, error) {
return sql.Open(azuread.DriverName, "sqlserver://azuresql.database.windows.net?database=yourdb&fedauth=ActiveDirectoryMSI")
}
func ConnectWithEnvironmentCredential() (*sql.DB, error) {
// Requires AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET environment variables
return sql.Open(azuread.DriverName, "sqlserver://azuresql.database.windows.net?database=yourdb&fedauth=ActiveDirectoryEnvironment")
}
func ConnectWithWorkloadIdentity() (*sql.DB, error) {
// For use in Kubernetes environments with workload identity
return sql.Open(azuread.DriverName, "sqlserver://azuresql.database.windows.net?database=yourdb&fedauth=ActiveDirectoryWorkloadIdentity")
}
func ConnectWithAzurePipelines() (*sql.DB, error) {
// For use in Azure DevOps Pipelines with explicit parameters
connStr := "sqlserver://azuresql.database.windows.net?database=yourdb&fedauth=ActiveDirectoryAzurePipelines"
connStr += "&user+id=" + url.QueryEscape("client-id@tenant-id")
connStr += "&serviceconnectionid=connection-id"
connStr += "&systemtoken=access-token"
return sql.Open(azuread.DriverName, connStr)
}
func ConnectWithAzurePipelinesEnvVars() (*sql.DB, error) {
// For use in Azure DevOps Pipelines with AzureCLI@2 or AzurePowerShell@5 tasks
// Environment variables are automatically set by these tasks
connStr := "sqlserver://azuresql.database.windows.net?database=yourdb&fedauth=ActiveDirectoryAzurePipelines"
connStr += "&systemtoken=access-token" // Only systemtoken needs to be provided
return sql.Open(azuread.DriverName, connStr)
}
Executing Stored Procedures
To run a stored procedure, set the query text to the procedure name:
var account = "abc"
_, err := db.ExecContext(ctx, "sp_RunMe",
sql.Named("ID", 123),
sql.Named("Account", sql.Out{Dest: &account}),
)
Reading Output Parameters from a Stored Procedure with Resultset
To read output parameters from a stored procedure with resultset, make sure you read all the rows before reading the output parameters:
sqltextcreate := `
CREATE PROCEDURE spwithoutputandrows
@bitparam BIT OUTPUT
AS BEGIN
SET @bitparam = 1
SELECT 'Row 1'
END
`
var bitout int64
rows, err := db.QueryContext(ctx, "spwithoutputandrows", sql.Named("bitparam", sql.Out{Dest: &bitout}))
var strrow string
for rows.Next() {
err = rows.Scan(&strrow)
}
fmt.Printf("bitparam is %d", bitout)
Caveat for local temporary tables
Due to protocol limitations, temporary tables will only be allocated on the connection
as a result of executing a query with zero parameters. The following query
will, due to the use of a parameter, execute in its own session,
and #mytemp will be de-allocated right away:
conn, err := pool.Conn(ctx)
defer conn.Close()
_, err := conn.ExecContext(ctx, "select @p1 as x into #mytemp", 1)
// at this point #mytemp is already dropped again as the session of the ExecContext is over
To work around this, always explicitly create the local temporary table in a query without any parameters. As a special case, the driver will then be able to execute the query directly on the connection-scoped session. The following example works:
conn, err := pool.Conn(ctx)
// Set us up so that temp table is always cleaned up, since conn.Close()
// merely returns conn to pool, rather than actually closing the connection.
defer func() {
_, _ = conn.ExecContext(ctx, "drop table #mytemp") // always clean up
conn.Close() // merely returns conn to pool
}()
// Since we not pass any parameters below, the query will execute on the scope of
// the connection and succeed in creating the table.
_, err := conn.ExecContext(ctx, "create table #mytemp ( x int )")
// #mytemp is now available even if you pass parameters
_, err := conn.ExecContext(ctx, "insert into #mytemp (x) values (@p1)", 1)
Return Status
To get the procedure return status, pass into the parameters a
*mssql.ReturnStatus. For example:
var rs mssql.ReturnStatus
_, err := db.ExecContext(ctx, "theproc", &rs)
log.Printf("status=%d", rs)
or
var rs mssql.ReturnStatus
_, err := db.QueryContext(ctx, "theproc", &rs)
for rows.Next() {
err = rows.Scan(&val)
}
log.Printf("status=%d", rs)
Limitation: ReturnStatus cannot be retrieved using QueryRow.
Parameters
The sqlserver driver uses normal MS SQL Server syntax and expects parameters in
the sql query to be in the form of either @Name or @p1 to @pN (ordinal position).
db.QueryContext(ctx, `select * from t where ID = @ID and Name = @p2;`, sql.Named("ID", 6), "Bob")
Parameter Types
To pass specific types to the query parameters, say varchar or date types,
you must convert the types to the type before passing in. The following types
are supported:
- string -> nvarchar
- mssql.VarChar -> varchar
- time.Time -> datetimeoffset or datetime (TDS version dependent)
- mssql.DateTime1 -> datetime
- mssql.DateTimeOffset -> datetimeoffset
- "github.com/golang-sql/civil".Date -> date
- "github.com/golang-sql/civil".DateTime -> datetime2
- "github.com/golang-sql/civil".Time -> time
- mssql.TVP -> Table Value Parameter (TDS version dependent)
- "github.com/shopspring/decimal".Decimal -> decimal
- mssql.Money -> money
Using an int parameter will send a 4 byte value (int) from a 32bit app and an 8 byte value (bigint) from a 64bit app.
To make sure your integer parameter matches the size of the SQL parameter, use the appropriate sized type like int32 or int8.
// If this is passed directly as a parameter,
// the SQL parameter generated would be nvarchar
name := "Bob"
// If the user_name is defined as varchar,
// it needs to be converted like this:
db.QueryContext(ctx, `select * from t2 where user_name = @p1;`, mssql.VarChar(name))
// Note: Mismatched data types on table and parameter may cause long running queries
Using Always Encrypted
The protocol and cryptography details for AE are detailed elsewhere.
Enablement
To enable AE on a connection, set the ColumnEncryption value to true on a config or pass columnencryption=true in the connection string.
Decryption and encryption won't succeed, however, without also including a decryption key provider. To avoid code size impacts on non-AE applications, key providers are not included by default.
Include the local certificate providers:
import (
"github.com/microsoft/go-mssqldb/aecmk/localcert"
)
You can also instantiate a key provider directly in code and hand it to a Connector instance.
c := mssql.NewConnectorConfig(myconfig)
c.RegisterCekProvider(providerName, MyProviderType{})
Decryption
If the correct key provider is included in your application, decryption of encrypted cells happens automatically with no extra server round trips.
Encryption
Encryption of parameters passed to Exec and Query variants requires an extra round trip per query to fetch the encryption metadata. If the error returned by a query attempt indicates a type mismatch between the parameter and the destination table, most likely your input type is not a strict match for the SQL Server data type of the destination. You may be using a Go string when you need to use one of the driver-specific aliases like VarChar or NVarCharMax.
*** NOTE *** - Currently char and varchar types do not include a collation parameter component so can't be used for inserting encrypted values.
https://github.com/microsoft/go-mssqldb/issues/129
Local certificate AE key provider
Key provider configuration is managed separately without any properties in the connection string.
The pfx provider exposes its instance as the variable PfxKeyProvider. You can give it passwords for certificates using SetCertificatePassword(pathToCertificate, path). Use an empty string or "*" as the path to use the same password for all certificates.
The MSSQL_CERTIFICATE_STORE provider exposes its instance as the variable WindowsCertificateStoreKeyProvider.
Both providers can be constrained to an allowed list of encryption key paths by appending paths to provider.AllowedLocations.
Azure Key Vault (AZURE_KEY_VAULT) key provider
Import this provider using github.com/microsoft/go-mssqldb/aecmk/akv
Constrain the provider to an allowed list of key vaults by appending vault host strings like "mykeyvault.vault.azure.net" to akv.KeyProvider.AllowedLocations.
Important Notes
- LastInsertId should
not be used with this driver (or SQL Server) due to how the TDS protocol
works. Please use the OUTPUT Clause
or add a
select ID = convert(bigint, SCOPE_IDENTITY());to the end of your query (ref SCOPE_IDENTITY). This will ensure you are getting the correct ID and will prevent a network round trip. - NewConnector may be used with OpenDB.
- Connector.SessionInitSQL may be set to set any driver specific session settings after the session has been reset. If empty the session will still be reset but use the database defaults in Go1.10+.
Features
- Can be used with SQL Server 2005 or newer
- Can be used with Microsoft Azure SQL Database
- Can be used on all go supported platforms (e.g. Linux, Mac OS X and Windows)
- Supports new date/time types: date, time, datetime2, datetimeoffset
- Supports string parameters longer than 8000 characters
- Supports encryption using SSL/TLS
- Supports SQL Server and Windows Authentication
- Supports Single-Sign-On on Windows
- Supports connections to AlwaysOn Availability Group listeners, including re-direction to read-only replicas.
- Supports query notifications
- Supports Kerberos Authentication
- Supports handling the
uniqueidentifierdata type with theUniqueIdentifierandNullUniqueIdentifiergo types - Pluggable Dialer implementations through
msdsn.ProtocolParsersandmsdsn.ProtocolDialers - A
namedpipepackage to support connections using named pipes (np:) on Windows - A
sharedmemorypackage to support connections using shared memory (lpc:) on Windows - Dedicated Administrator Connection (DAC) is supported using
adminprotocol - Always Encrypted
MSSQL_CERTIFICATE_STOREprovider on Windowspfxprovider on Linux and Windows
Tests
go test is used for testing. A running instance of MSSQL server is required.
Environment variables are used to pass login information.
Example:
env SQLSERVER_DSN=sqlserver://user:pass@hostname/instance?database=test1 go test
AZURESERVER_DSN environment variable provides the connection string for Azure Active Directory-based authentication. If it's not set the AAD test will be skipped.
Deprecated
These features still exist in the driver, but they are are deprecated.
Query Parameter Token Replace (driver "mssql")
If you use the driver name "mssql" (rather then "sqlserver") the SQL text will be loosly parsed and an attempt to extract identifiers using one of
- ?
- ?nnn
- :nnn
- $nnn
will be used. This is not recommended with SQL Server.
There is at least one existing won't fix issue with the query parsing.
Use the native "@Name" parameters instead with the "sqlserver" driver name.
Known Issues
-
SQL Server 2008 and 2008 R2 engine cannot handle login records when SSL encryption is not disabled. To fix SQL Server 2008 R2 issue, install SQL Server 2008 R2 Service Pack 2. To fix SQL Server 2008 issue, install Microsoft SQL Server 2008 Service Pack 3 and Cumulative update package 3 for SQL Server 2008 SP3. More information: http://support.microsoft.com/kb/2653857
-
Bulk copy does not yet support encrypting column values using Always Encrypted. Tracked in #127
Development
Quick Start with Dev Containers
The easiest way to develop and test the driver is using the included Dev Container, which works with:
- VS Code: Install the Dev Containers extension, open this repo, and click "Reopen in Container"
- GitHub Codespaces: Click the "Code" button on GitHub and select "Create codespace"
The dev container includes:
- Go 1.25 with all development tools
- SQL Server 2025 ready for integration tests
- go-sqlcmd (uses this driver!)
- Pre-configured environment variables for tests
Once inside the container, run the full test suite:
go test ./...
Manual Setup
If you prefer to set up your environment manually, see CONTRIBUTING.md for requirements. You'll need:
- Go 1.25 or higher
- Access to a SQL Server instance (2017 or later recommended)
Contributing
This project is a fork of https://github.com/denisenkom/go-mssqldb and welcomes new and previous contributors. For more informaton on contributing to this project, please see Contributing.
For more information on the roadmap for go-mssqldb, project plans are available for viewing and discussion.
Documentation
- Wiki - Additional guides and troubleshooting
- pkg.go.dev - API reference documentation
- Examples - Sample code for common scenarios
Microsoft Open Source Code of Conduct
This project has adopted the Microsoft Open Source Code of Conduct.
Resources:
- Microsoft Open Source Code of Conduct
- Microsoft Code of Conduct FAQ
- Contact [email protected] with questions or concerns
Documentation
¶
Overview ¶
Package mssql is Microsoft's official Go driver for SQL Server and Azure SQL Database.
This package implements the TDS protocol used to connect to Microsoft SQL Server (SQL Server 2005 and later) and Azure SQL Database.
Driver Registration ¶
This package registers the following drivers:
sqlserver: preferred driver; uses native "@" parameter placeholder names and does no pre-processing. mssql: legacy compatibility driver (deprecated); performs query token replacement and may be removed in a future release.
Use "sqlserver" as the driver name with database/sql.Open:
db, err := sql.Open("sqlserver", "sqlserver://user:password@localhost:1433?database=mydb")
Connection String Formats ¶
URL format (recommended):
sqlserver://user:password@localhost:1433?database=mydb sqlserver://user:password@localhost/instance?database=mydb
ADO format:
server=localhost;user id=sa;password=secret;database=mydb
ODBC format:
odbc:server=localhost;user id=sa;password=secret;database=mydb
Query Parameters ¶
Use "@ParameterName" or "@p1", "@p2", etc. for query parameters:
// Named parameters
db.Query("SELECT * FROM users WHERE id = @ID", sql.Named("ID", 123))
// Positional parameters
db.Query("SELECT * FROM users WHERE id = @p1", 123)
Azure AD Authentication ¶
For Azure Active Directory authentication, import the azuread subpackage:
import "github.com/microsoft/go-mssqldb/azuread"
db, err := sql.Open(azuread.DriverName,
"sqlserver://server.database.windows.net?database=mydb&fedauth=ActiveDirectoryDefault&encrypt=true&TrustServerCertificate=false")
Features ¶
- SQL Server 2005+ and Azure SQL Database support
- Windows Authentication, SQL Authentication, Azure AD, Kerberos
- Always Encrypted column encryption
- Bulk copy operations via CopyIn
- Stored procedures with output parameters
- Table-valued parameters
- Named pipes and shared memory on Windows
For complete documentation, see https://github.com/microsoft/go-mssqldb
Example (AzureADConnection) ¶
Example_azureADConnection shows connection strings for Azure AD authentication. Import "github.com/microsoft/go-mssqldb/azuread" and use azuread.DriverName. Always enable encryption with certificate validation for Azure SQL.
package main
import (
"fmt"
_ "github.com/microsoft/go-mssqldb"
)
func main() {
// DefaultAzureCredential (recommended for most scenarios)
// Enable TLS with certificate validation for Azure SQL
defaultCred := "sqlserver://server.database.windows.net?database=mydb&fedauth=ActiveDirectoryDefault&encrypt=true&TrustServerCertificate=false"
fmt.Println("DefaultAzureCredential:", defaultCred)
// Managed Identity
msiCred := "sqlserver://server.database.windows.net?database=mydb&fedauth=ActiveDirectoryMSI&encrypt=true&TrustServerCertificate=false"
fmt.Println("Managed Identity:", msiCred)
}
Output: DefaultAzureCredential: sqlserver://server.database.windows.net?database=mydb&fedauth=ActiveDirectoryDefault&encrypt=true&TrustServerCertificate=false Managed Identity: sqlserver://server.database.windows.net?database=mydb&fedauth=ActiveDirectoryMSI&encrypt=true&TrustServerCertificate=false
Example (BuildConnectionString) ¶
Example_buildConnectionString demonstrates programmatically building a connection string using the net/url package.
package main
import (
"fmt"
"net/url"
_ "github.com/microsoft/go-mssqldb"
)
func main() {
query := url.Values{}
query.Add("database", "mydb")
query.Add("connection timeout", "30")
query.Add("encrypt", "true")
u := &url.URL{
Scheme: "sqlserver",
User: url.UserPassword("username", "password"),
Host: "localhost:1433",
RawQuery: query.Encode(),
}
connStr := u.String()
fmt.Println("Built connection string")
// Use with sql.Open:
// db, err := sql.Open("sqlserver", connStr)
_ = connStr
}
Output: Built connection string
Example (ConnectionString) ¶
Example_connectionString shows the basic connection string format. Use "sqlserver" as the driver name (not "mssql").
package main
import (
"fmt"
_ "github.com/microsoft/go-mssqldb"
)
func main() {
// URL format connection string (recommended)
connStr := "sqlserver://user:password@localhost:1433?database=mydb"
fmt.Println("URL format:", connStr)
// ADO format connection string
adoConnStr := "server=localhost;user id=sa;password=secret;database=mydb"
fmt.Println("ADO format:", adoConnStr)
// ODBC format connection string
odbcConnStr := "odbc:server=localhost;user id=sa;password=secret;database=mydb"
fmt.Println("ODBC format:", odbcConnStr)
}
Output: URL format: sqlserver://user:password@localhost:1433?database=mydb ADO format: server=localhost;user id=sa;password=secret;database=mydb ODBC format: odbc:server=localhost;user id=sa;password=secret;database=mydb
Example (NamedParameterSyntax) ¶
Example_namedParameterSyntax shows the correct parameter syntax for queries. Use @ParameterName with sql.Named() for named parameters.
package main
import (
"fmt"
_ "github.com/microsoft/go-mssqldb"
)
func main() {
// Named parameter syntax - use @ParameterName
query := "SELECT * FROM users WHERE id = @ID AND active = @Active"
fmt.Println("Named parameters:", query)
// Positional parameter syntax - use @p1, @p2, etc.
positionalQuery := "SELECT * FROM users WHERE id = @p1 AND active = @p2"
fmt.Println("Positional parameters:", positionalQuery)
}
Output: Named parameters: SELECT * FROM users WHERE id = @ID AND active = @Active Positional parameters: SELECT * FROM users WHERE id = @p1 AND active = @p2
Example (StoredProcedureSyntax) ¶
Example_storedProcedureSyntax shows how to call stored procedures with output parameters.
package main
import (
"fmt"
_ "github.com/microsoft/go-mssqldb"
)
func main() {
// Stored procedure call syntax with named parameters
procCall := "EXEC sp_MyProcedure @InputParam = @Input, @OutputParam = @Output OUTPUT"
fmt.Println("Stored procedure:", procCall)
// In Go code, use sql.Named with sql.Out for output parameters:
// var outputValue string
// _, err := db.ExecContext(ctx, "sp_MyProcedure",
// sql.Named("Input", "test value"),
// sql.Named("Output", sql.Out{Dest: &outputValue}),
// )
}
Output: Stored procedure: EXEC sp_MyProcedure @InputParam = @Input, @OutputParam = @Output OUTPUT
Index ¶
- Constants
- Variables
- func CopyIn(table string, options BulkOptions, columns ...string) string
- func IsSkipField(tvpTagValue string, isTvpValue bool, jsonTagValue string, isJsonTagValue bool) bool
- func NewAccessTokenConnector(dsn string, tokenProvider func() (string, error)) (driver.Connector, error)
- func SetContextLogger(ctxLogger ContextLogger)
- func SetLogger(logger Logger)
- type Bulk
- type BulkOptions
- type ColumnEncryptionType
- type Conn
- func (c *Conn) Begin() (driver.Tx, error)
- func (c *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error)
- func (c *Conn) CheckNamedValue(nv *driver.NamedValue) error
- func (c *Conn) Close() error
- func (c *Conn) Commit() error
- func (c *Conn) CreateBulk(table string, columns []string) (_ *Bulk)
- func (c *Conn) CreateBulkContext(ctx context.Context, table string, columns []string) (_ *Bulk)
- func (c *Conn) IsValid() bool
- func (c *Conn) Ping(ctx context.Context) error
- func (c *Conn) Prepare(query string) (driver.Stmt, error)
- func (c *Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error)
- func (c *Conn) ResetSession(ctx context.Context) error
- func (c *Conn) Rollback() error
- type Connector
- func NewActiveDirectoryTokenConnector(config msdsn.Config, adalWorkflow byte, ...) (*Connector, error)
- func NewConnector(dsn string) (*Connector, error)
- func NewConnectorConfig(config msdsn.Config) *Connector
- func NewConnectorWithAccessTokenProvider(dsn string, tokenProvider func(ctx context.Context) (string, error)) (*Connector, error)
- func NewConnectorWithProcessQueryText(config msdsn.Config) *Connector
- func NewSecurityTokenConnector(config msdsn.Config, tokenProvider func(ctx context.Context) (string, error)) (*Connector, error)
- type ContextLogger
- type DataValue
- type DateTime1
- type DateTimeOffset
- type Dialer
- type Driver
- type Error
- func (e Error) Error() string
- func (e Error) SQLErrorClass() uint8
- func (e Error) SQLErrorLineNo() int32
- func (e Error) SQLErrorMessage() string
- func (e Error) SQLErrorNumber() int32
- func (e Error) SQLErrorProcName() string
- func (e Error) SQLErrorServerName() string
- func (e Error) SQLErrorState() uint8
- func (e Error) String() string
- type HostDialer
- type Logger
- type Money
- type MssqlBulk
- type MssqlBulkOptions
- type MssqlConn
- type MssqlDriver
- type MssqlProtocolDialer
- type MssqlResult
- type MssqlRows
- type MssqlStmt
- type NChar
- type NVarCharMax
- type NullDate
- type NullDateTime
- type NullTime
- type NullUniqueIdentifier
- func (n NullUniqueIdentifier) MarshalJSON() ([]byte, error)
- func (n NullUniqueIdentifier) MarshalText() (text []byte, err error)
- func (n *NullUniqueIdentifier) Scan(v interface{}) error
- func (n NullUniqueIdentifier) String() string
- func (n *NullUniqueIdentifier) UnmarshalJSON(b []byte) error
- func (n NullUniqueIdentifier) Value() (driver.Value, error)
- type RWCBuffer
- type Result
- type RetryableError
- type ReturnStatus
- type Rows
- func (rc *Rows) Close() error
- func (r *Rows) ColumnTypeDatabaseTypeName(index int) string
- func (r *Rows) ColumnTypeLength(index int) (int64, bool)
- func (r *Rows) ColumnTypeNullable(index int) (nullable, ok bool)
- func (r *Rows) ColumnTypePrecisionScale(index int) (int64, int64, bool)
- func (r *Rows) ColumnTypeScanType(index int) reflect.Type
- func (rc *Rows) Columns() (res []string)
- func (rc *Rows) HasNextResultSet() bool
- func (rc *Rows) Next(dest []driver.Value) error
- func (rc *Rows) NextResultSet() error
- type Rowsq
- func (rc *Rowsq) Close() error
- func (r *Rowsq) ColumnTypeDatabaseTypeName(index int) string
- func (r *Rowsq) ColumnTypeLength(index int) (int64, bool)
- func (r *Rowsq) ColumnTypeNullable(index int) (nullable, ok bool)
- func (r *Rowsq) ColumnTypePrecisionScale(index int) (int64, int64, bool)
- func (r *Rowsq) ColumnTypeScanType(index int) reflect.Type
- func (rc *Rowsq) Columns() (res []string)
- func (rc *Rowsq) HasNextResultSet() bool
- func (rc *Rowsq) Next(dest []driver.Value) error
- func (rc *Rowsq) NextResultSet() error
- type ServerError
- type Stmt
- func (s *Stmt) Close() error
- func (s *Stmt) Exec(args []driver.Value) (driver.Result, error)
- func (s *Stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error)
- func (s *Stmt) NumInput() int
- func (s *Stmt) Query(args []driver.Value) (driver.Rows, error)
- func (s *Stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error)
- func (s *Stmt) SetQueryNotification(id, options string, timeout time.Duration)
- type StreamError
- type TSQLQuoter
- type TVP
- type UniqueIdentifier
- type VarChar
- type VarCharMax
Examples ¶
Constants ¶
const ( CertificateStoreKeyProvider = "MSSQL_CERTIFICATE_STORE" CspKeyProvider = "MSSQL_CSP_PROVIDER" CngKeyProvider = "MSSQL_CNG_STORE" AzureKeyVaultKeyProvider = "AZURE_KEY_VAULT" JavaKeyProvider = "MSSQL_JAVA_KEYSTORE" KeyEncryptionAlgorithm = "RSA_OAEP" )
const ( // FedAuthLibraryLiveIDCompactToken specifies the Microsoft Live ID Compact Token authentication scheme FedAuthLibraryLiveIDCompactToken = 0x00 // FedAuthLibrarySecurityToken specifies a token-based authentication where the token is available // without additional information provided during the login sequence. FedAuthLibrarySecurityToken = 0x01 // FedAuthLibraryADAL specifies a token-based authentication where a token is obtained during the // login sequence using the server SPN and STS URL provided by the server during login. FedAuthLibraryADAL = 0x02 // FedAuthLibraryReserved is used to indicate that no federated authentication scheme applies. FedAuthLibraryReserved = 0x7F )
Federated authentication library affects the login data structure and message sequence.
const ( // FedAuthADALWorkflowPassword uses a username/password to obtain a token from Active Directory FedAuthADALWorkflowPassword = 0x01 // fedAuthADALWorkflowPassword uses the Windows identity to obtain a token from Active Directory FedAuthADALWorkflowIntegrated = 0x02 // FedAuthADALWorkflowMSI uses the managed identity service to obtain a token FedAuthADALWorkflowMSI = 0x03 // FedAuthADALWorkflowNone does not need to obtain token FedAuthADALWorkflowNone = 0x04 )
Federated authentication ADAL workflow affects the mechanism used to authenticate.
Variables ¶
var ( ErrorEmptyTVPTypeName = errors.New("TypeName must not be empty") ErrorTypeSlice = errors.New("TVP must be slice type") ErrorTypeSliceIsEmpty = errors.New("TVP mustn't be null value") ErrorSkip = errors.New("all fields mustn't skip") ErrorObjectName = errors.New("wrong tvp name") ErrorWrongTyping = errors.New("the number of elements in columnStr and tvpFieldIndexes do not align") )
Functions ¶
func CopyIn ¶
func CopyIn(table string, options BulkOptions, columns ...string) string
CopyIn creates a bulk import statement that can be passed to Prepare.
table is the destination object name. It is treated as an object name and is quoted before it is sent to the server, so a name that is not a regular identifier does not need to be delimited by the caller. It may be qualified, as in "schema.table" or "database.schema.table", and individual parts may be delimited, as in "[my schema].[my table]".
Because the destination is always an object name, a value that relied on being spliced into the statement as raw text no longer resolves. Pass "table" and options.Tablock rather than "table WITH (TABLOCK)". A name that cannot identify an object, because it is empty or has more than four parts, is reported before any statement is sent.
columns are the destination column names, in the order their values are passed to Exec.
Each options.Order entry names one or more columns to declare the data is already sorted by, as in "id" or "id ASC, name DESC". Column names are quoted the same way table is. A column name is separated from an optional trailing ASC or DESC sort direction by whitespace, and from the next column by a comma, so a column whose name ends in "asc" or "desc" or contains a comma has to be delimited by the caller to be told apart from a direction or a separator, as in "[sort desc]" or "[order, id]".
Example ¶
This example shows how to perform bulk imports
//go:build go1.10
// +build go1.10
package main
import (
"database/sql"
"log"
"strings"
"unicode/utf8"
mssql "github.com/microsoft/go-mssqldb"
)
const (
createTestTable = `CREATE TABLE test_table(
id int IDENTITY(1,1) NOT NULL,
test_nvarchar nvarchar(50) NULL,
test_varchar varchar(50) NULL,
test_float float NULL,
test_datetime2_3 datetime2(3) NULL,
test_bitn bit NULL,
test_bigint bigint NOT NULL,
test_geom geometry NULL,
CONSTRAINT PK_table_test_id PRIMARY KEY CLUSTERED
(
id ASC
) ON [PRIMARY]);`
dropTestTable = "IF OBJECT_ID('test_table', 'U') IS NOT NULL DROP TABLE test_table;"
)
// This example shows how to perform bulk imports
func main() {
connString := makeConnURL().String()
db, err := sql.Open("sqlserver", connString)
if err != nil {
log.Fatal("Open connection failed:", err.Error())
}
defer db.Close()
txn, err := db.Begin()
if err != nil {
log.Fatal(err)
}
// Create table
_, err = db.Exec(createTestTable)
if err != nil {
log.Fatal(err)
}
defer db.Exec(dropTestTable)
// mssqldb.CopyIn creates string to be consumed by Prepare
stmt, err := txn.Prepare(mssql.CopyIn("test_table", mssql.BulkOptions{}, "test_varchar", "test_nvarchar", "test_float", "test_bigint"))
if err != nil {
log.Fatal(err.Error())
}
for i := 0; i < 10; i++ {
_, err = stmt.Exec(generateString(0, 30), generateStringUnicode(0, 30), i, i)
if err != nil {
log.Fatal(err.Error())
}
}
result, err := stmt.Exec()
if err != nil {
log.Fatal(err)
}
err = stmt.Close()
if err != nil {
log.Fatal(err)
}
err = txn.Commit()
if err != nil {
log.Fatal(err)
}
rowCount, _ := result.RowsAffected()
log.Printf("%d row copied\n", rowCount)
log.Printf("bye\n")
}
func generateString(x int, n int) string {
letters := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
b := make([]byte, n)
for i := range b {
b[i] = letters[(x+i)%len(letters)]
}
return string(b)
}
func generateStringUnicode(x int, n int) string {
letters := []byte("ab©💾é?ghïjklmnopqЯ☀tuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := &strings.Builder{}
for i := 0; i < n; i++ {
r, sz := utf8.DecodeRune(letters[x%len(letters):])
x += sz
b.WriteRune(r)
}
return b.String()
}
Output:
func IsSkipField ¶
func NewAccessTokenConnector ¶
func NewAccessTokenConnector(dsn string, tokenProvider func() (string, error)) (driver.Connector, error)
NewAccessTokenConnector creates a new connector from a DSN and a token provider. The token provider func will be called when a new connection is requested and should return a valid access token. The returned connector may be used with sql.OpenDB.
func SetContextLogger ¶
func SetContextLogger(ctxLogger ContextLogger)
SetContextLogger sets a ContextLogger for both driver instances ("mssql" and "sqlserver"). Use this to get callbacks from go-mssqldb with additional information and extra details that you can log in the format of your choice. You can set either a ContextLogger or a Logger, but not both. Calling SetContextLogger will overwrite any Logger you set with SetLogger.
func SetLogger ¶
func SetLogger(logger Logger)
SetLogger sets a Logger for both driver instances ("mssql" and "sqlserver"). Use this to have go-msqldb log additional information in a format it picks. You can set either a Logger or a ContextLogger, but not both. Calling SetLogger will overwrite any ContextLogger you set with SetContextLogger.
Types ¶
type Bulk ¶
type Bulk struct {
Options BulkOptions
Debug bool
// contains filtered or unexported fields
}
type BulkOptions ¶
type ColumnEncryptionType ¶ added in v1.6.0
type ColumnEncryptionType int
var ( ColumnEncryptionPlainText ColumnEncryptionType = 0 ColumnEncryptionDeterministic ColumnEncryptionType = 1 ColumnEncryptionRandomized ColumnEncryptionType = 2 )
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
func (*Conn) CheckNamedValue ¶
func (c *Conn) CheckNamedValue(nv *driver.NamedValue) error
func (*Conn) CreateBulkContext ¶
func (*Conn) Ping ¶
Ping is used to check if the remote server is available and satisfies the Pinger interface.
func (*Conn) PrepareContext ¶
type Connector ¶
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, except DNS resolution unless
// the dialer implements the HostDialer.
//
// 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.
Example ¶
This example shows the usage of Connector type
//go:build go1.10
// +build go1.10
package main
import (
"context"
"database/sql"
"flag"
"fmt"
"log"
"net/url"
"strconv"
mssql "github.com/microsoft/go-mssqldb"
)
var (
debug = flag.Bool("debug", false, "enable debugging")
password = flag.String("password", "", "the database password")
port *int = flag.Int("port", 1433, "the database port")
server = flag.String("server", ".", "the database server")
user = flag.String("user", "", "the database user")
)
const (
createTableSql = "CREATE TABLE TestAnsiNull (bitcol bit, charcol char(1));"
dropTableSql = "IF OBJECT_ID('TestAnsiNull', 'U') IS NOT NULL DROP TABLE TestAnsiNull;"
insertQuery1 = "INSERT INTO TestAnsiNull VALUES (0, NULL);"
insertQuery2 = "INSERT INTO TestAnsiNull VALUES (1, 'a');"
selectNullFilter = "SELECT bitcol FROM TestAnsiNull WHERE charcol = NULL;"
selectNotNullFilter = "SELECT bitcol FROM TestAnsiNull WHERE charcol <> NULL;"
)
func makeConnURL() *url.URL {
flag.Parse()
if *debug {
fmt.Printf(" password:%s\n", *password)
fmt.Printf(" port:%d\n", *port)
fmt.Printf(" server:%s\n", *server)
fmt.Printf(" user:%s\n", *user)
}
params, err := mssql.GetConnParams()
if err == nil && params != nil {
return params.URL()
}
var userInfo *url.Userinfo
if *user != "" {
userInfo = url.UserPassword(*user, *password)
}
return &url.URL{
Scheme: "sqlserver",
Host: *server + ":" + strconv.Itoa(*port),
User: userInfo,
}
}
// This example shows the usage of Connector type
func main() {
connString := makeConnURL().String()
if *debug {
fmt.Printf(" connString:%s\n", connString)
}
// Create a new connector object by calling NewConnector
connector, err := mssql.NewConnector(connString)
if err != nil {
log.Println(err)
return
}
// Use SessionInitSql to set any options that cannot be set with the dsn string
// With ANSI_NULLS set to ON, compare NULL data with = NULL or <> NULL will return 0 rows
connector.SessionInitSQL = "SET ANSI_NULLS ON"
// Pass connector to sql.OpenDB to get a sql.DB object
db := sql.OpenDB(connector)
defer db.Close()
// Create and populate table
_, err = db.Exec(createTableSql)
if err != nil {
log.Println(err)
return
}
defer db.Exec(dropTableSql)
_, err = db.Exec(insertQuery1)
if err != nil {
log.Println(err)
return
}
_, err = db.Exec(insertQuery2)
if err != nil {
log.Println(err)
return
}
var bitval bool
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// (*Row) Scan should return ErrNoRows since ANSI_NULLS is set to ON
err = db.QueryRowContext(ctx, selectNullFilter).Scan(&bitval)
if err != nil {
if err.Error() != "sql: no rows in result set" {
log.Println(err)
return
}
} else {
log.Println("Expects an ErrNoRows error. No error is returned")
return
}
// (*Row) Scan should return ErrNoRows since ANSI_NULLS is set to ON
err = db.QueryRowContext(ctx, selectNotNullFilter).Scan(&bitval)
if err != nil {
if err.Error() != "sql: no rows in result set" {
log.Println(err)
return
}
} else {
log.Println("Expects an ErrNoRows error. No error is returned")
return
}
// Set ANSI_NULLS to OFF
connector.SessionInitSQL = "SET ANSI_NULLS OFF"
// (*Row) Scan should copy data to bitval
err = db.QueryRowContext(ctx, selectNullFilter).Scan(&bitval)
if err != nil {
log.Println(err)
return
}
if bitval != false {
log.Println("Incorrect value retrieved.")
return
}
// (*Row) Scan should copy data to bitval
err = db.QueryRowContext(ctx, selectNotNullFilter).Scan(&bitval)
if err != nil {
log.Println(err)
return
}
if bitval != true {
log.Println("Incorrect value retrieved.")
return
}
}
Output:
func NewActiveDirectoryTokenConnector ¶
func NewActiveDirectoryTokenConnector(config msdsn.Config, adalWorkflow byte, tokenProvider func(ctx context.Context, serverSPN, stsURL string) (string, error)) (*Connector, error)
newADALTokenConnector creates a new connector from a Config and a Active Directory token provider. Token provider implementations are called during federated authentication login sequences where the server provides a service principal name and security token service endpoint that should be used to obtain the token. Implementations should contact the security token service specified and obtain the appropriate token, or return an error to indicate why a token is not available.
The returned connector may be used with sql.OpenDB.
func NewConnector ¶
NewConnector creates a new connector from a DSN. The returned connector may be used with sql.OpenDB.
func NewConnectorConfig ¶
NewConnectorConfig creates a new Connector for a DSN Config struct. The returned connector may be used with sql.OpenDB.
func NewConnectorWithAccessTokenProvider ¶ added in v0.15.0
func NewConnectorWithAccessTokenProvider(dsn string, tokenProvider func(ctx context.Context) (string, error)) (*Connector, error)
NewConnectorWithAccessTokenProvider creates a new connector from a DSN using the given access token provider. The returned connector may be used with sql.OpenDB.
func NewConnectorWithProcessQueryText ¶ added in v1.10.0
NewConnectorWithProcessQueryText creates a new Connector for a DSN Config struct that pre-processes query text, converting "?" and ":N" placeholder parameters to "@pN" parameter names. This enables compatibility with libraries like sqlx that use "?" as parameter placeholders. The pre-processing behavior is equivalent to that of the deprecated "mssql" driver name. The returned connector may be used with sql.OpenDB.
func NewSecurityTokenConnector ¶
func NewSecurityTokenConnector(config msdsn.Config, tokenProvider func(ctx context.Context) (string, error)) (*Connector, error)
newSecurityTokenConnector creates a new connector from a Config and a token provider. When invoked, token provider implementations should contact the security token service specified and obtain the appropriate token, or return an error to indicate why a token is not available. The returned connector may be used with sql.OpenDB.
func (*Connector) RegisterCekProvider ¶ added in v1.6.0
func (c *Connector) RegisterCekProvider(name string, provider aecmk.ColumnEncryptionKeyProvider)
RegisterCekProvider associates the given provider with the named key store. If an entry of the given name already exists, that entry is overwritten
type ContextLogger ¶
ContextLogger is an interface that provides more information than Logger and lets you log messages yourself. This gives you more information to log (e.g. trace IDs in the context), more control over the logging activity (e.g. log it, trace it, or log and trace it, depending on the class of message), and lets you log in exactly the format you want.
type DateTimeOffset ¶
DateTimeOffset encodes parameters to DateTimeOffset, preserving the UTC offset.
Example ¶
This example shows how to insert and retrieve date and time types data
//go:build go1.10
// +build go1.10
package main
import (
"database/sql"
"fmt"
"log"
"time"
"github.com/golang-sql/civil"
mssql "github.com/microsoft/go-mssqldb"
)
// This example shows how to insert and retrieve date and time types data
func main() {
connString := makeConnURL().String()
db, err := sql.Open("sqlserver", connString)
if err != nil {
log.Fatal("Open connection failed:", err.Error())
}
defer db.Close()
insertDateTime(db)
retrieveDateTime(db)
retrieveDateTimeOutParam(db)
}
func insertDateTime(db *sql.DB) {
_, err := db.Exec("CREATE TABLE datetimeTable (timeCol TIME, dateCol DATE, smalldatetimeCol SMALLDATETIME, datetimeCol DATETIME, datetime2Col DATETIME2, datetimeoffsetCol DATETIMEOFFSET)")
if err != nil {
log.Fatal(err)
}
stmt, err := db.Prepare("INSERT INTO datetimeTable VALUES(@p1, @p2, @p3, @p4, @p5, @p6)")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
tin, err := time.Parse(time.RFC3339, "2006-01-02T22:04:05.787-07:00")
if err != nil {
log.Fatal(err)
}
var timeCol civil.Time = civil.TimeOf(tin)
var dateCol civil.Date = civil.DateOf(tin)
var smalldatetimeCol string = "2006-01-02 22:04:00"
var datetimeCol mssql.DateTime1 = mssql.DateTime1(tin)
var datetime2Col civil.DateTime = civil.DateTimeOf(tin)
var datetimeoffsetCol mssql.DateTimeOffset = mssql.DateTimeOffset(tin)
_, err = stmt.Exec(timeCol, dateCol, smalldatetimeCol, datetimeCol, datetime2Col, datetimeoffsetCol)
if err != nil {
log.Fatal(err)
}
}
func retrieveDateTime(db *sql.DB) {
rows, err := db.Query("SELECT timeCol, dateCol, smalldatetimeCol, datetimeCol, datetime2Col, datetimeoffsetCol FROM datetimeTable")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var c1, c2, c3, c4, c5, c6 time.Time
for rows.Next() {
err = rows.Scan(&c1, &c2, &c3, &c4, &c5, &c6)
if err != nil {
log.Fatal(err)
}
fmt.Printf("c1: %+v; c2: %+v; c3: %+v; c4: %+v; c5: %+v; c6: %+v;\n", c1, c2, c3, c4, c5, c6)
}
}
func retrieveDateTimeOutParam(db *sql.DB) {
CreateProcSql := `
CREATE PROCEDURE OutDatetimeProc
@timeOutParam TIME OUTPUT,
@dateOutParam DATE OUTPUT,
@smalldatetimeOutParam SMALLDATETIME OUTPUT,
@datetimeOutParam DATETIME OUTPUT,
@datetime2OutParam DATETIME2 OUTPUT,
@datetimeoffsetOutParam DATETIMEOFFSET OUTPUT
AS
SET NOCOUNT ON
SET @timeOutParam = '22:04:05.7870015'
SET @dateOutParam = '2006-01-02'
SET @smalldatetimeOutParam = '2006-01-02 22:04:00'
SET @datetimeOutParam = '2006-01-02 22:04:05.787'
SET @datetime2OutParam = '2006-01-02 22:04:05.7870015'
SET @datetimeoffsetOutParam = '2006-01-02 22:04:05.7870015 -07:00'`
_, err := db.Exec(CreateProcSql)
if err != nil {
log.Fatal(err)
}
var (
timeOutParam, datetime2OutParam, datetimeoffsetOutParam mssql.DateTimeOffset
dateOutParam, datetimeOutParam mssql.DateTime1
smalldatetimeOutParam string
)
_, err = db.Exec("OutDatetimeProc",
sql.Named("timeOutParam", sql.Out{Dest: &timeOutParam}),
sql.Named("dateOutParam", sql.Out{Dest: &dateOutParam}),
sql.Named("smalldatetimeOutParam", sql.Out{Dest: &smalldatetimeOutParam}),
sql.Named("datetimeOutParam", sql.Out{Dest: &datetimeOutParam}),
sql.Named("datetime2OutParam", sql.Out{Dest: &datetime2OutParam}),
sql.Named("datetimeoffsetOutParam", sql.Out{Dest: &datetimeoffsetOutParam}))
if err != nil {
log.Fatal(err)
}
fmt.Printf("timeOutParam: %+v; dateOutParam: %+v; smalldatetimeOutParam: %s; datetimeOutParam: %+v; datetime2OutParam: %+v; datetimeoffsetOutParam: %+v;\n", time.Time(timeOutParam), time.Time(dateOutParam), smalldatetimeOutParam, time.Time(datetimeOutParam), time.Time(datetime2OutParam), time.Time(datetimeoffsetOutParam))
}
Output:
type Driver ¶
type Driver struct {
// contains filtered or unexported fields
}
func (*Driver) OpenConnector ¶
OpenConnector opens a new connector. Useful to dial with a context.
func (*Driver) SetContextLogger ¶
func (d *Driver) SetContextLogger(ctxLogger ContextLogger)
SetContextLogger sets a ContextLogger for the driver instance on which you call it. Use this to get callbacks from go-mssqldb with additional information and extra details that you can log in the format of your choice. You can set either a ContextLogger or a Logger, but not both. Calling SetContextLogger will overwrite any Logger you set with SetLogger.
func (*Driver) SetLogger ¶
SetLogger sets a Logger for the driver instance on which you call it. Use this to have go-msqldb log additional information in a format it picks. You can set either a Logger or a ContextLogger, but not both. Calling SetLogger will overwrite any ContextLogger you set with SetContextLogger.
type Error ¶
type Error struct {
Number int32
State uint8
Class uint8
Message string
ServerName string
ProcName string
LineNo int32
// All lists all errors that were received from first to last.
// This includes the last one, which is described in the other members.
All []Error
}
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.
func (Error) SQLErrorClass ¶
func (Error) SQLErrorLineNo ¶
func (Error) SQLErrorMessage ¶
Example ¶
package main
import (
"fmt"
)
func main() {
// 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 callUsingMSSQL() error {
return nil
}
Output:
func (Error) SQLErrorNumber ¶
SQLErrorNumber returns the SQL Server error number.
Example ¶
package main
import (
"fmt"
)
func main() {
// 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")
}
}
}
func callUsingMSSQL() error {
return nil
}
Output:
func (Error) SQLErrorProcName ¶
func (Error) SQLErrorServerName ¶
func (Error) SQLErrorState ¶
type HostDialer ¶ added in v1.4.0
HostDialer should be used if the dialer is proxying requests to a different network and DNS should be resolved in that other network
type Logger ¶
type Logger interface {
Printf(format string, v ...interface{})
Println(v ...interface{})
}
Logger is an interface you can implement to have the go-msqldb driver automatically log detailed information on your behalf
type Money ¶ added in v1.9.5
type Money[D decimal.Decimal | decimal.NullDecimal] struct { Decimal D }
type MssqlBulk ¶
type MssqlBulk = Bulk // Deprecated: users should transition to the new name when possible.
type MssqlBulkOptions ¶
type MssqlBulkOptions = BulkOptions // Deprecated: users should transition to the new name when possible.
type MssqlConn ¶
type MssqlConn = Conn // Deprecated: users should transition to the new name when possible.
type MssqlDriver ¶
type MssqlDriver = Driver // Deprecated: users should transition to the new name when possible.
type MssqlProtocolDialer ¶ added in v0.18.0
type MssqlResult ¶
type MssqlResult = Result // Deprecated: users should transition to the new name when possible.
type MssqlRows ¶
type MssqlRows = Rows // Deprecated: users should transition to the new name when possible.
type MssqlStmt ¶
type MssqlStmt = Stmt // Deprecated: users should transition to the new name when possible.
type NChar ¶ added in v1.6.0
type NChar string
NChar is used to encode a string parameter as NChar instead of a sized NVarChar
type NVarCharMax ¶
type NVarCharMax string
NVarCharMax is used to encode a string parameter as NVarChar(max) instead of a sized NVarChar
type NullDate ¶ added in v1.10.0
func (NullDate) MarshalText ¶ added in v1.10.0
func (*NullDate) UnmarshalText ¶ added in v1.10.0
type NullDateTime ¶ added in v1.10.0
func (NullDateTime) MarshalText ¶ added in v1.10.0
func (n NullDateTime) MarshalText() ([]byte, error)
func (*NullDateTime) Scan ¶ added in v1.10.0
func (n *NullDateTime) Scan(value interface{}) error
func (NullDateTime) String ¶ added in v1.10.0
func (n NullDateTime) String() string
func (*NullDateTime) UnmarshalText ¶ added in v1.10.0
func (n *NullDateTime) UnmarshalText(data []byte) error
type NullTime ¶ added in v1.10.0
func (NullTime) MarshalText ¶ added in v1.10.0
func (*NullTime) UnmarshalText ¶ added in v1.10.0
type NullUniqueIdentifier ¶ added in v1.7.0
type NullUniqueIdentifier struct {
UUID UniqueIdentifier
Valid bool // Valid is true if UUID is not NULL
}
func (NullUniqueIdentifier) MarshalJSON ¶ added in v1.8.1
func (n NullUniqueIdentifier) MarshalJSON() ([]byte, error)
func (NullUniqueIdentifier) MarshalText ¶ added in v1.7.0
func (n NullUniqueIdentifier) MarshalText() (text []byte, err error)
func (*NullUniqueIdentifier) Scan ¶ added in v1.7.0
func (n *NullUniqueIdentifier) Scan(v interface{}) error
func (NullUniqueIdentifier) String ¶ added in v1.7.0
func (n NullUniqueIdentifier) String() string
func (*NullUniqueIdentifier) UnmarshalJSON ¶ added in v1.7.0
func (n *NullUniqueIdentifier) UnmarshalJSON(b []byte) error
type RWCBuffer ¶ added in v1.6.0
type RWCBuffer struct {
// contains filtered or unexported fields
}
type Result ¶
type Result struct {
// contains filtered or unexported fields
}
func (*Result) LastInsertId ¶
Example ¶
This example shows the usage of Connector type
connString := makeConnURL().String()
db, err := sql.Open("sqlserver", connString)
if err != nil {
log.Fatal("Open connection failed:", err.Error())
}
defer db.Close()
// Create table
_, err = db.Exec("create table foo (bar int identity, baz int unique);")
if err != nil {
log.Fatal(err)
}
defer db.Exec("if object_id('foo', 'U') is not null drop table foo;")
// Attempt to retrieve scope identity using LastInsertId
res, err := db.Exec("insert into foo (baz) values (1)")
if err != nil {
log.Fatal(err)
}
n, err := res.LastInsertId()
if err != nil {
log.Print(err)
// Gets error: LastInsertId is not supported. Please use the OUTPUT clause or add `select ID = convert(bigint, SCOPE_IDENTITY())` to the end of your query.
}
log.Printf("LastInsertId: %d\n", n)
// Retrieve scope identity by adding 'select ID = convert(bigint, SCOPE_IDENTITY())' to the end of the query
rows, err := db.Query("insert into foo (baz) values (10); select ID = convert(bigint, SCOPE_IDENTITY())")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var lastInsertId1 int64
for rows.Next() {
rows.Scan(&lastInsertId1)
log.Printf("LastInsertId from SCOPE_IDENTITY(): %d\n", lastInsertId1)
}
// Retrieve scope identity by 'output inserted``
var lastInsertId2 int64
err = db.QueryRow("insert into foo (baz) output inserted.bar values (100)").Scan(&lastInsertId2)
if err != nil {
log.Fatal(err)
}
log.Printf("LastInsertId from output inserted: %d\n", lastInsertId2)
func (*Result) RowsAffected ¶
type RetryableError ¶
type RetryableError struct {
// contains filtered or unexported fields
}
RetryableError is returned when an error was caused by a bad connection at the start of a query and can be safely retried using database/sql's automatic retry logic.
In many cases database/sql's retry logic will transparently handle this error, the retried call will return successfully, and you won't even see this error. However, you may see this error if the retry logic cannot successfully handle the error. In that case you can get the underlying error by calling this error's UnWrap function.
func (RetryableError) Error ¶
func (r RetryableError) Error() string
func (RetryableError) Is ¶
func (r RetryableError) Is(err error) bool
func (RetryableError) Unwrap ¶
func (r RetryableError) Unwrap() error
type ReturnStatus ¶
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 ¶
type Rows struct {
// contains filtered or unexported fields
}
Rows represents the non-experimental data/sql model for Query and QueryContext
Example (Usingmessages) ¶
This example shows the usage of sqlexp/Messages
//go:build go1.10
// +build go1.10
package main
import (
"context"
"database/sql"
"fmt"
"log"
"github.com/golang-sql/sqlexp"
mssql "github.com/microsoft/go-mssqldb"
)
const (
msgQuery = `select 'name' as Name
PRINT N'This is a message'
select 199
RAISERROR (N'Testing!' , 11, 1)
select 300
`
)
// This example shows the usage of sqlexp/Messages
func main() {
connString := makeConnURL().String()
// Create a new connector object by calling NewConnector
connector, err := mssql.NewConnector(connString)
if err != nil {
log.Println(err)
return
}
// Pass connector to sql.OpenDB to get a sql.DB object
db := sql.OpenDB(connector)
defer db.Close()
retmsg := &sqlexp.ReturnMessage{}
ctx := context.Background()
rows, err := db.QueryContext(ctx, msgQuery, retmsg)
if err != nil {
log.Fatalf("QueryContext failed: %v", err)
}
active := true
for active {
msg := retmsg.Message(ctx)
switch m := msg.(type) {
case sqlexp.MsgNotice:
fmt.Println(m.Message)
case sqlexp.MsgNext:
inresult := true
for inresult {
inresult = rows.Next()
if inresult {
cols, err := rows.Columns()
if err != nil {
log.Fatalf("Columns failed: %v", err)
}
fmt.Println(cols)
var d interface{}
if err = rows.Scan(&d); err == nil {
fmt.Println(d)
}
}
}
case sqlexp.MsgNextResultSet:
active = rows.NextResultSet()
case sqlexp.MsgError:
fmt.Println("Error:", m.Error)
case sqlexp.MsgRowsAffected:
fmt.Println("Rows affected:", m.Count)
}
}
}
Output:
func (*Rows) ColumnTypeDatabaseTypeName ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) HasNextResultSet ¶
func (*Rows) NextResultSet ¶
type Rowsq ¶
type Rowsq struct {
// contains filtered or unexported fields
}
Rowsq implements the sqlexp messages model for Query and QueryContext Theory: We could also implement the non-experimental model this way
func (*Rowsq) ColumnTypeDatabaseTypeName ¶
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 (*Rowsq) ColumnTypeLength ¶
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 (*Rowsq) ColumnTypeNullable ¶
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 (*Rowsq) ColumnTypePrecisionScale ¶
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 (*Rowsq) ColumnTypeScanType ¶
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 (*Rowsq) Columns ¶
ProcessSingleResponse queues MsgNext for every columns token. data/sql calls Columns during the app's call to Next.
func (*Rowsq) HasNextResultSet ¶
In Message Queue mode, we always claim another resultset could be on the way to avoid Rows being closed prematurely
func (*Rowsq) NextResultSet ¶
Scans to the end of the current statement being processed Note that the caller may not have read all the rows in the prior set
type ServerError ¶
type ServerError struct {
// contains filtered or unexported fields
}
ServerError is returned when the server got a fatal error that aborts the process and severs the connection.
To get the errors returned before the process was aborted, unwrap this error or call errors.As with a pointer to an mssql.Error variable.
func (ServerError) Error ¶
func (e ServerError) Error() string
func (ServerError) Unwrap ¶
func (e ServerError) Unwrap() error
type Stmt ¶
type Stmt struct {
// contains filtered or unexported fields
}
func (*Stmt) ExecContext ¶
func (*Stmt) QueryContext ¶
type StreamError ¶
type StreamError struct {
InnerError error
}
func (StreamError) Error ¶
func (e StreamError) Error() string
type TSQLQuoter ¶ added in v1.6.0
type TSQLQuoter struct {
}
TSQLQuoter implements sqlexp.Quoter
func (TSQLQuoter) ID ¶ added in v1.6.0
func (TSQLQuoter) ID(name string) string
ID quotes identifiers such as schema, table, or column names. This implementation handles multi-part names.
func (TSQLQuoter) Value ¶ added in v1.6.0
func (TSQLQuoter) Value(v interface{}) string
Value quotes database values such as string or []byte types as strings that are suitable and safe to embed in SQL text. The returned value of a string will include all surrounding quotes.
If a value type is not supported it must panic.
type TVP ¶
type TVP struct {
//TypeName mustn't be default value
TypeName string
//Value must be the slice, mustn't be nil
Value interface{}
}
TVP is driver type, which allows supporting Table Valued Parameters (TVP) in SQL Server
Example ¶
This example shows how to use tvp type
const (
createTable = "CREATE TABLE Location (Name VARCHAR(50), CostRate INT, Availability BIT, ModifiedDate DATETIME2)"
createTVP = `CREATE TYPE LocationTableType AS TABLE
(LocationName VARCHAR(50),
CostRate INT)`
dropTVP = "IF type_id('LocationTableType') IS NOT NULL DROP TYPE LocationTableType"
createProc = `CREATE PROCEDURE dbo.usp_InsertProductionLocation
@TVP LocationTableType READONLY
AS
SET NOCOUNT ON
INSERT INTO Location
(
Name,
CostRate,
Availability,
ModifiedDate)
SELECT *, 0,GETDATE()
FROM @TVP`
dropProc = "IF OBJECT_ID('dbo.usp_InsertProductionLocation', 'P') IS NOT NULL DROP PROCEDURE dbo.usp_InsertProductionLocation"
execTvp = "exec dbo.usp_InsertProductionLocation @TVP;"
)
type LocationTableTvp struct {
LocationName string
LocationCountry string `tvp:"-"`
CostRate int64
Currency string `json:"-"`
}
connString := makeConnURL().String()
db, err := sql.Open("sqlserver", connString)
if err != nil {
log.Fatal("Open connection failed:", err.Error())
}
defer db.Close()
_, err = db.Exec(createTable)
if err != nil {
log.Fatal(err)
}
_, err = db.Exec(createTVP)
if err != nil {
log.Fatal(err)
}
defer db.Exec(dropTVP)
_, err = db.Exec(createProc)
if err != nil {
log.Fatal(err)
}
defer db.Exec(dropProc)
locationTableTypeData := []LocationTableTvp{
{
LocationName: "Alberta",
LocationCountry: "Canada",
CostRate: 0,
Currency: "CAD",
},
{
LocationName: "British Columbia",
LocationCountry: "Canada",
CostRate: 1,
Currency: "CAD",
},
}
tvpType := mssql.TVP{
TypeName: "LocationTableType",
Value: locationTableTypeData,
}
_, err = db.Exec(execTvp, sql.Named("TVP", tvpType))
if err != nil {
log.Fatal(err)
} else {
for _, locationData := range locationTableTypeData {
fmt.Printf("Data for location %s, %s has been inserted.\n", locationData.LocationName, locationData.LocationCountry)
}
}
type UniqueIdentifier ¶
type UniqueIdentifier [16]byte
func (UniqueIdentifier) MarshalText ¶
func (u UniqueIdentifier) MarshalText() (text []byte, err error)
MarshalText converts Uniqueidentifier to bytes corresponding to the stringified hexadecimal representation of the Uniqueidentifier e.g., "AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA" -> [65 65 65 65 65 65 65 65 45 65 65 65 65 45 65 65 65 65 45 65 65 65 65 65 65 65 65 65 65 65 65]
func (*UniqueIdentifier) Scan ¶
func (u *UniqueIdentifier) Scan(v interface{}) error
func (UniqueIdentifier) String ¶
func (u UniqueIdentifier) String() string
func (*UniqueIdentifier) UnmarshalJSON ¶ added in v1.4.0
func (u *UniqueIdentifier) UnmarshalJSON(b []byte) error
Unmarshals a string representation of a UniqueIndentifier to bytes "01234567-89AB-CDEF-0123-456789ABCDEF" -> [48, 49, 50, 51, 52, 53, 54, 55, 45, 56, 57, 65, 66, 45, 67, 68, 69, 70, 45, 48, 49, 50, 51, 45, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70]
type VarChar ¶
type VarChar string
VarChar is used to encode a string parameter as VarChar instead of a sized NVarChar
type VarCharMax ¶
type VarCharMax string
VarCharMax is used to encode a string parameter as VarChar(max) instead of a sized NVarChar
Source Files
¶
- accesstokenconnector.go
- auth_unix.go
- buf.go
- bulkcopy.go
- bulkcopy_sql.go
- civil_null.go
- columnencryptionkey.go
- convert.go
- doc.go
- encrypt.go
- error.go
- fedauth.go
- log.go
- money.go
- mssql.go
- mssql_go110.go
- mssql_go118.go
- mssql_go19.go
- net.go
- protocol.go
- protocol_go113.go
- quoter.go
- rpc.go
- session.go
- tds.go
- timezone.go
- token.go
- token_string.go
- tran.go
- tvp_go19.go
- types.go
- ucs22str.go
- uniqueidentifier.go
- uniqueidentifier_null.go
- version.go
Directories
¶
| Path | Synopsis |
|---|---|
|
bach splits a single script containing multiple batches separated by a keyword into multiple scripts.
|
bach splits a single script containing multiple batches separated by a keyword into multiple scripts. |
|
examples
|
|
|
azuread-service-principal
command
|
|
|
bulk
command
|
|
|
channel_binding
command
|
|
|
routine
command
|
|
|
simple
command
|
|
|
tsql
command
|
|
|
tvp
command
|
|
|
aws-rds-proxy-iam-auth
module
|
|
|
azuread-accesstoken
module
|
|
|
krb5
Package krb5 implements the integratedauth.IntegratedAuthenticator interface in order to provide kerberos/active directory (Windows) based authentication.
|
Package krb5 implements the integratedauth.IntegratedAuthenticator interface in order to provide kerberos/active directory (Windows) based authentication. |
|
internal
|
|
|
gopkg.in/natefinch/npipe.v2
Package npipe provides a pure Go wrapper around Windows named pipes.
|
Package npipe provides a pure Go wrapper around Windows named pipes. |
|
querytext
Package querytext is the old query parser and parameter substitute process.
|
Package querytext is the old query parser and parameter substitute process. |