Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. The user domain sensitive to the case which is defined in the connection string.
  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. The `database` must be specified when connecting with `Application Intent` set to `ReadOnly`.
  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. ### Azure Active Directory authentication - preview
  86. The configuration of functionality might change in the future.
  87. Azure Active Directory (AAD) access tokens are relatively short lived and need to be
  88. valid when a new connection is made. Authentication is supported using a callback func that
  89. provides a fresh and valid token using a connector:
  90. ``` golang
  91. conn, err := mssql.NewAccessTokenConnector(
  92. "Server=test.database.windows.net;Database=testdb",
  93. tokenProvider)
  94. if err != nil {
  95. // handle errors in DSN
  96. }
  97. db := sql.OpenDB(conn)
  98. ```
  99. Where `tokenProvider` is a function that returns a fresh access token or an error. None of these statements
  100. actually trigger the retrieval of a token, this happens when the first statment is issued and a connection
  101. is created.
  102. ## Executing Stored Procedures
  103. To run a stored procedure, set the query text to the procedure name:
  104. ```go
  105. var account = "abc"
  106. _, err := db.ExecContext(ctx, "sp_RunMe",
  107. sql.Named("ID", 123),
  108. sql.Named("Account", sql.Out{Dest: &account}),
  109. )
  110. ```
  111. ## Reading Output Parameters from a Stored Procedure with Resultset
  112. To read output parameters from a stored procedure with resultset, make sure you read all the rows before reading the output parameters:
  113. ```go
  114. sqltextcreate := `
  115. CREATE PROCEDURE spwithoutputandrows
  116. @bitparam BIT OUTPUT
  117. AS BEGIN
  118. SET @bitparam = 1
  119. SELECT 'Row 1'
  120. END
  121. `
  122. var bitout int64
  123. rows, err := db.QueryContext(ctx, "spwithoutputandrows", sql.Named("bitparam", sql.Out{Dest: &bitout}))
  124. var strrow string
  125. for rows.Next() {
  126. err = rows.Scan(&strrow)
  127. }
  128. fmt.Printf("bitparam is %d", bitout)
  129. ```
  130. ## Caveat for local temporary tables
  131. Due to protocol limitations, temporary tables will only be allocated on the connection
  132. as a result of executing a query with zero parameters. The following query
  133. will, due to the use of a parameter, execute in its own session,
  134. and `#mytemp` will be de-allocated right away:
  135. ```go
  136. conn, err := pool.Conn(ctx)
  137. defer conn.Close()
  138. _, err := conn.ExecContext(ctx, "select @p1 as x into #mytemp", 1)
  139. // at this point #mytemp is already dropped again as the session of the ExecContext is over
  140. ```
  141. To work around this, always explicitly create the local temporary
  142. table in a query without any parameters. As a special case, the driver
  143. will then be able to execute the query directly on the
  144. connection-scoped session. The following example works:
  145. ```go
  146. conn, err := pool.Conn(ctx)
  147. // Set us up so that temp table is always cleaned up, since conn.Close()
  148. // merely returns conn to pool, rather than actually closing the connection.
  149. defer func() {
  150. _, _ = conn.ExecContext(ctx, "drop table #mytemp") // always clean up
  151. conn.Close() // merely returns conn to pool
  152. }()
  153. // Since we not pass any parameters below, the query will execute on the scope of
  154. // the connection and succeed in creating the table.
  155. _, err := conn.ExecContext(ctx, "create table #mytemp ( x int )")
  156. // #mytemp is now available even if you pass parameters
  157. _, err := conn.ExecContext(ctx, "insert into #mytemp (x) values (@p1)", 1)
  158. ```
  159. ## Return Status
  160. To get the procedure return status, pass into the parameters a
  161. `*mssql.ReturnStatus`. For example:
  162. ```
  163. var rs mssql.ReturnStatus
  164. _, err := db.ExecContext(ctx, "theproc", &rs)
  165. log.Printf("status=%d", rs)
  166. ```
  167. or
  168. ```
  169. var rs mssql.ReturnStatus
  170. _, err := db.QueryContext(ctx, "theproc", &rs)
  171. for rows.Next() {
  172. err = rows.Scan(&val)
  173. }
  174. log.Printf("status=%d", rs)
  175. ```
  176. Limitation: ReturnStatus cannot be retrieved using `QueryRow`.
  177. ## Parameters
  178. The `sqlserver` driver uses normal MS SQL Server syntax and expects parameters in
  179. the sql query to be in the form of either `@Name` or `@p1` to `@pN` (ordinal position).
  180. ```go
  181. db.QueryContext(ctx, `select * from t where ID = @ID and Name = @p2;`, sql.Named("ID", 6), "Bob")
  182. ```
  183. ### Parameter Types
  184. To pass specific types to the query parameters, say `varchar` or `date` types,
  185. you must convert the types to the type before passing in. The following types
  186. are supported:
  187. * string -> nvarchar
  188. * mssql.VarChar -> varchar
  189. * time.Time -> datetimeoffset or datetime (TDS version dependent)
  190. * mssql.DateTime1 -> datetime
  191. * mssql.DateTimeOffset -> datetimeoffset
  192. * "github.com/golang-sql/civil".Date -> date
  193. * "github.com/golang-sql/civil".DateTime -> datetime2
  194. * "github.com/golang-sql/civil".Time -> time
  195. * mssql.TVP -> Table Value Parameter (TDS version dependent)
  196. ## Important Notes
  197. * [LastInsertId](https://golang.org/pkg/database/sql/#Result.LastInsertId) should
  198. not be used with this driver (or SQL Server) due to how the TDS protocol
  199. works. Please use the [OUTPUT Clause](https://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql)
  200. or add a `select ID = convert(bigint, SCOPE_IDENTITY());` to the end of your
  201. query (ref [SCOPE_IDENTITY](https://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql)).
  202. This will ensure you are getting the correct ID and will prevent a network round trip.
  203. * [NewConnector](https://godoc.org/github.com/denisenkom/go-mssqldb#NewConnector)
  204. may be used with [OpenDB](https://golang.org/pkg/database/sql/#OpenDB).
  205. * [Connector.SessionInitSQL](https://godoc.org/github.com/denisenkom/go-mssqldb#Connector.SessionInitSQL)
  206. may be set to set any driver specific session settings after the session
  207. has been reset. If empty the session will still be reset but use the database
  208. defaults in Go1.10+.
  209. ## Features
  210. * Can be used with SQL Server 2005 or newer
  211. * Can be used with Microsoft Azure SQL Database
  212. * Can be used on all go supported platforms (e.g. Linux, Mac OS X and Windows)
  213. * Supports new date/time types: date, time, datetime2, datetimeoffset
  214. * Supports string parameters longer than 8000 characters
  215. * Supports encryption using SSL/TLS
  216. * Supports SQL Server and Windows Authentication
  217. * Supports Single-Sign-On on Windows
  218. * Supports connections to AlwaysOn Availability Group listeners, including re-direction to read-only replicas.
  219. * Supports query notifications
  220. ## Tests
  221. `go test` is used for testing. A running instance of MSSQL server is required.
  222. Environment variables are used to pass login information.
  223. Example:
  224. env SQLSERVER_DSN=sqlserver://user:pass@hostname/instance?database=test1 go test
  225. ## Deprecated
  226. These features still exist in the driver, but they are are deprecated.
  227. ### Query Parameter Token Replace (driver "mssql")
  228. If you use the driver name "mssql" (rather then "sqlserver") the SQL text
  229. will be loosly parsed and an attempt to extract identifiers using one of
  230. * ?
  231. * ?nnn
  232. * :nnn
  233. * $nnn
  234. will be used. This is not recommended with SQL Server.
  235. There is at least one existing `won't fix` issue with the query parsing.
  236. Use the native "@Name" parameters instead with the "sqlserver" driver name.
  237. ## Known Issues
  238. * SQL Server 2008 and 2008 R2 engine cannot handle login records when SSL encryption is not disabled.
  239. To fix SQL Server 2008 R2 issue, install SQL Server 2008 R2 Service Pack 2.
  240. To fix SQL Server 2008 issue, install Microsoft SQL Server 2008 Service Pack 3 and Cumulative update package 3 for SQL Server 2008 SP3.
  241. More information: http://support.microsoft.com/kb/2653857