You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. # A pure Go MSSQL driver for Go's database/sql package
  2. [![GoDoc](https://godoc.org/github.com/denisenkom/go-mssqldb?status.svg)](http://godoc.org/github.com/denisenkom/go-mssqldb)
  3. [![Build status](https://ci.appveyor.com/api/projects/status/jrln8cs62wj9i0a2?svg=true)](https://ci.appveyor.com/project/denisenkom/go-mssqldb)
  4. [![codecov](https://codecov.io/gh/denisenkom/go-mssqldb/branch/master/graph/badge.svg)](https://codecov.io/gh/denisenkom/go-mssqldb)
  5. ## Install
  6. Requires Go 1.8 or above.
  7. Install with `go get github.com/denisenkom/go-mssqldb` .
  8. ## Connection Parameters and DSN
  9. The recommended connection string uses a URL format:
  10. `sqlserver://username:password@host/instance?param1=value&param2=value`
  11. Other supported formats are listed below.
  12. ### Common parameters:
  13. * `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.
  14. * `password`
  15. * `database`
  16. * `connection 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.
  17. * `dial timeout` - in seconds (default is 15), set to 0 for no timeout
  18. * `encrypt`
  19. * `disable` - Data send between client and server is not encrypted.
  20. * `false` - Data sent between client and server is not encrypted beyond the login packet. (Default)
  21. * `true` - Data sent between client and server is encrypted.
  22. * `app name` - The application name (default is go-mssqldb)
  23. ### Connection parameters for ODBC and ADO style connection strings:
  24. * `server` - host or host\instance (default localhost)
  25. * `port` - used only when there is no instance in server (default 1433)
  26. ### Less common parameters:
  27. * `keepAlive` - in seconds; 0 to disable (default is 30)
  28. * `failoverpartner` - host or host\instance (default is no partner).
  29. * `failoverport` - used only when there is no instance in failoverpartner (default 1433)
  30. * `packet size` - in bytes; 512 to 32767 (default is 4096)
  31. * Encrypted connections have a maximum packet size of 16383 bytes
  32. * Further information on usage: https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/configure-the-network-packet-size-server-configuration-option
  33. * `log` - logging flags (default 0/no logging, 63 for full logging)
  34. * 1 log errors
  35. * 2 log messages
  36. * 4 log rows affected
  37. * 8 trace sql statements
  38. * 16 log statement parameters
  39. * 32 log transaction begin/end
  40. * `TrustServerCertificate`
  41. * false - Server certificate is checked. Default is false if encypt is specified.
  42. * 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.
  43. * `certificate` - The file that contains the public key certificate of the CA that signed the SQL Server certificate. The specified certificate overrides the go platform specific CA certificates.
  44. * `hostNameInCertificate` - Specifies the Common Name (CN) in the server certificate. Default value is the server host.
  45. * `ServerSPN` - The kerberos SPN (Service Principal Name) for the server. Default is MSSQLSvc/host:port.
  46. * `Workstation ID` - The workstation name (default is the host name)
  47. * `ApplicationIntent` - Can be given the value `ReadOnly` to initiate a read-only connection to an Availability Group listener.
  48. ### The connection string can be specified in one of three formats:
  49. 1. URL: with `sqlserver` scheme. username and password appears before the host. Any instance appears as
  50. the first segment in the path. All other options are query parameters. Examples:
  51. * `sqlserver://username:password@host/instance?param1=value&param2=value`
  52. * `sqlserver://username:password@host:port?param1=value&param2=value`
  53. * `sqlserver://sa@localhost/SQLExpress?database=master&connection+timeout=30` // `SQLExpress instance.
  54. * `sqlserver://sa:mypass@localhost?database=master&connection+timeout=30` // username=sa, password=mypass.
  55. * `sqlserver://sa:mypass@localhost:1234?database=master&connection+timeout=30` // port 1234 on localhost.
  56. * `sqlserver://sa:my%7Bpass@somehost?connection+timeout=30` // password is "my{pass"
  57. A string of this format can be constructed using the `URL` type in the `net/url` package.
  58. ```go
  59. query := url.Values{}
  60. query.Add("app name", "MyAppName")
  61. u := &url.URL{
  62. Scheme: "sqlserver",
  63. User: url.UserPassword(username, password),
  64. Host: fmt.Sprintf("%s:%d", hostname, port),
  65. // Path: instance, // if connecting to an instance instead of a port
  66. RawQuery: query.Encode(),
  67. }
  68. db, err := sql.Open("sqlserver", u.String())
  69. ```
  70. 2. ADO: `key=value` pairs separated by `;`. Values may not contain `;`, leading and trailing whitespace is ignored.
  71. Examples:
  72. * `server=localhost\\SQLExpress;user id=sa;database=master;app name=MyAppName`
  73. * `server=localhost;user id=sa;database=master;app name=MyAppName`
  74. 3. ODBC: Prefix with `odbc`, `key=value` pairs separated by `;`. Allow `;` by wrapping
  75. values in `{}`. Examples:
  76. * `odbc:server=localhost\\SQLExpress;user id=sa;database=master;app name=MyAppName`
  77. * `odbc:server=localhost;user id=sa;database=master;app name=MyAppName`
  78. * `odbc:server=localhost;user id=sa;password={foo;bar}` // Value marked with `{}`, password is "foo;bar"
  79. * `odbc:server=localhost;user id=sa;password={foo{bar}` // Value marked with `{}`, password is "foo{bar"
  80. * `odbc:server=localhost;user id=sa;password={foobar }` // Value marked with `{}`, password is "foobar "
  81. * `odbc:server=localhost;user id=sa;password=foo{bar` // Literal `{`, password is "foo{bar"
  82. * `odbc:server=localhost;user id=sa;password=foo}bar` // Literal `}`, password is "foo}bar"
  83. * `odbc:server=localhost;user id=sa;password={foo{bar}` // Literal `{`, password is "foo{bar"
  84. * `odbc:server=localhost;user id=sa;password={foo}}bar}` // Escaped `} with `}}`, password is "foo}bar"
  85. ## Executing Stored Procedures
  86. To run a stored procedure, set the query text to the procedure name:
  87. ```go
  88. var account = "abc"
  89. _, err := db.ExecContext(ctx, "sp_RunMe",
  90. sql.Named("ID", 123),
  91. sql.Named("Account", sql.Out{Dest: &account}),
  92. )
  93. ```
  94. ## Reading Output Parameters from a Stored Procedure with Resultset
  95. To read output parameters from a stored procedure with resultset, make sure you read all the rows before reading the output parameters:
  96. ```go
  97. sqltextcreate := `
  98. CREATE PROCEDURE spwithoutputandrows
  99. @bitparam BIT OUTPUT
  100. AS BEGIN
  101. SET @bitparam = 1
  102. SELECT 'Row 1'
  103. END
  104. `
  105. var bitout int64
  106. rows, err := db.QueryContext(ctx, "spwithoutputandrows", sql.Named("bitparam", sql.Out{Dest: &bitout}))
  107. var strrow string
  108. for rows.Next() {
  109. err = rows.Scan(&strrow)
  110. }
  111. fmt.Printf("bitparam is %d", bitout)
  112. ```
  113. ## Caveat for local temporary tables
  114. Due to protocol limitations, temporary tables will only be allocated on the connection
  115. as a result of executing a query with zero parameters. The following query
  116. will, due to the use of a parameter, execute in its own session,
  117. and `#mytemp` will be de-allocated right away:
  118. ```go
  119. conn, err := pool.Conn(ctx)
  120. defer conn.Close()
  121. _, err := conn.ExecContext(ctx, "select @p1 as x into #mytemp", 1)
  122. // at this point #mytemp is already dropped again as the session of the ExecContext is over
  123. ```
  124. To work around this, always explicitly create the local temporary
  125. table in a query without any parameters. As a special case, the driver
  126. will then be able to execute the query directly on the
  127. connection-scoped session. The following example works:
  128. ```go
  129. conn, err := pool.Conn(ctx)
  130. // Set us up so that temp table is always cleaned up, since conn.Close()
  131. // merely returns conn to pool, rather than actually closing the connection.
  132. defer func() {
  133. _, _ = conn.ExecContext(ctx, "drop table #mytemp") // always clean up
  134. conn.Close() // merely returns conn to pool
  135. }()
  136. // Since we not pass any parameters below, the query will execute on the scope of
  137. // the connection and succeed in creating the table.
  138. _, err := conn.ExecContext(ctx, "create table #mytemp ( x int )")
  139. // #mytemp is now available even if you pass parameters
  140. _, err := conn.ExecContext(ctx, "insert into #mytemp (x) values (@p1)", 1)
  141. ```
  142. ## Return Status
  143. To get the procedure return status, pass into the parameters a
  144. `*mssql.ReturnStatus`. For example:
  145. ```
  146. var rs mssql.ReturnStatus
  147. _, err := db.ExecContext(ctx, "theproc", &rs)
  148. log.Printf("status=%d", rs)
  149. ```
  150. or
  151. ```
  152. var rs mssql.ReturnStatus
  153. _, err := db.QueryContext(ctx, "theproc", &rs)
  154. for rows.Next() {
  155. err = rows.Scan(&val)
  156. }
  157. log.Printf("status=%d", rs)
  158. ```
  159. Limitation: ReturnStatus cannot be retrieved using `QueryRow`.
  160. ## Parameters
  161. The `sqlserver` driver uses normal MS SQL Server syntax and expects parameters in
  162. the sql query to be in the form of either `@Name` or `@p1` to `@pN` (ordinal position).
  163. ```go
  164. db.QueryContext(ctx, `select * from t where ID = @ID and Name = @p2;`, sql.Named("ID", 6), "Bob")
  165. ```
  166. ### Parameter Types
  167. To pass specific types to the query parameters, say `varchar` or `date` types,
  168. you must convert the types to the type before passing in. The following types
  169. are supported:
  170. * string -> nvarchar
  171. * mssql.VarChar -> varchar
  172. * time.Time -> datetimeoffset or datetime (TDS version dependent)
  173. * mssql.DateTime1 -> datetime
  174. * mssql.DateTimeOffset -> datetimeoffset
  175. * "cloud.google.com/go/civil".Date -> date
  176. * "cloud.google.com/go/civil".DateTime -> datetime2
  177. * "cloud.google.com/go/civil".Time -> time
  178. * mssql.TVP -> Table Value Parameter (TDS version dependent)
  179. ## Important Notes
  180. * [LastInsertId](https://golang.org/pkg/database/sql/#Result.LastInsertId) should
  181. not be used with this driver (or SQL Server) due to how the TDS protocol
  182. works. Please use the [OUTPUT Clause](https://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql)
  183. or add a `select ID = convert(bigint, SCOPE_IDENTITY());` to the end of your
  184. query (ref [SCOPE_IDENTITY](https://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql)).
  185. This will ensure you are getting the correct ID and will prevent a network round trip.
  186. * [NewConnector](https://godoc.org/github.com/denisenkom/go-mssqldb#NewConnector)
  187. may be used with [OpenDB](https://golang.org/pkg/database/sql/#OpenDB).
  188. * [Connector.SessionInitSQL](https://godoc.org/github.com/denisenkom/go-mssqldb#Connector.SessionInitSQL)
  189. may be set to set any driver specific session settings after the session
  190. has been reset. If empty the session will still be reset but use the database
  191. defaults in Go1.10+.
  192. ## Features
  193. * Can be used with SQL Server 2005 or newer
  194. * Can be used with Microsoft Azure SQL Database
  195. * Can be used on all go supported platforms (e.g. Linux, Mac OS X and Windows)
  196. * Supports new date/time types: date, time, datetime2, datetimeoffset
  197. * Supports string parameters longer than 8000 characters
  198. * Supports encryption using SSL/TLS
  199. * Supports SQL Server and Windows Authentication
  200. * Supports Single-Sign-On on Windows
  201. * Supports connections to AlwaysOn Availability Group listeners, including re-direction to read-only replicas.
  202. * Supports query notifications
  203. ## Tests
  204. `go test` is used for testing. A running instance of MSSQL server is required.
  205. Environment variables are used to pass login information.
  206. Example:
  207. env SQLSERVER_DSN=sqlserver://user:pass@hostname/instance?database=test1 go test
  208. ## Deprecated
  209. These features still exist in the driver, but they are are deprecated.
  210. ### Query Parameter Token Replace (driver "mssql")
  211. If you use the driver name "mssql" (rather then "sqlserver") the SQL text
  212. will be loosly parsed and an attempt to extract identifiers using one of
  213. * ?
  214. * ?nnn
  215. * :nnn
  216. * $nnn
  217. will be used. This is not recommended with SQL Server.
  218. There is at least one existing `won't fix` issue with the query parsing.
  219. Use the native "@Name" parameters instead with the "sqlserver" driver name.
  220. ## Known Issues
  221. * SQL Server 2008 and 2008 R2 engine cannot handle login records when SSL encryption is not disabled.
  222. To fix SQL Server 2008 R2 issue, install SQL Server 2008 R2 Service Pack 2.
  223. To fix SQL Server 2008 issue, install Microsoft SQL Server 2008 Service Pack 3 and Cumulative update package 3 for SQL Server 2008 SP3.
  224. More information: http://support.microsoft.com/kb/2653857