forked from dotnet/SqlClient
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSqlConnection.xml
1292 lines (985 loc) · 112 KB
/
SqlConnection.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0"?>
<docs>
<members name="SqlConnection">
<SqlConnection>
<summary>Represents a connection to a SQL Server database. This class cannot be inherited.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
A <xref:Microsoft.Data.SqlClient.SqlConnection> object represents a unique session to a SQL Server data source. With a client/server database system, it is equivalent to a network connection to the server. <xref:Microsoft.Data.SqlClient.SqlConnection> is used together with <xref:Microsoft.Data.SqlClient.SqlDataAdapter> and <xref:Microsoft.Data.SqlClient.SqlCommand> to increase performance when connecting to a Microsoft SQL Server database. For all third-party SQL Server products and other OLE DB-supported data sources, use <xref:System.Data.OleDb.OleDbConnection>.
When you create an instance of <xref:Microsoft.Data.SqlClient.SqlConnection>, all properties are set to their initial values. For a list of these values, see the <xref:Microsoft.Data.SqlClient.SqlConnection> constructor.
See <xref:Microsoft.Data.SqlClient.SqlConnection.ConnectionString%2A> for a list of the keywords in a connection string.
If the <xref:Microsoft.Data.SqlClient.SqlConnection> goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling `Close` or `Dispose`. `Close` and `Dispose` are functionally equivalent. If the connection pooling value `Pooling` is set to `true` or `yes`, the underlying connection is returned back to the connection pool. On the other hand, if `Pooling` is set to `false` or `no`, the underlying connection to the server is actually closed.
> [!NOTE]
> Login and logout events will not be raised on the server when a connection is fetched from or returned to the connection pool, because the connection is not actually closed when it is returned to the connection pool. For more information, see [SQL Server Connection Pooling (ADO.NET)](/sql/connect/ado-net/sql-server-connection-pooling).
To ensure that connections are always closed, open the connection inside of a `using` block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.
```vb
Using connection As New SqlConnection(connectionString)
connection.Open()
' Do work here; connection closed on following line.
End Using
```
```csharp
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Do work here; connection closed on following line.
}
```
> [!NOTE]
> To deploy high-performance applications, you must use connection pooling. When you use the .NET Framework Data Provider for SQL Server, you do not have to enable connection pooling because the provider manages this automatically, although you can modify some settings. For more information, see [SQL Server Connection Pooling (ADO.NET)](/sql/connect/ado-net/sql-server-connection-pooling).
If a <xref:Microsoft.Data.SqlClient.SqlException> is generated by the method executing a <xref:Microsoft.Data.SqlClient.SqlCommand>, the <xref:Microsoft.Data.SqlClient.SqlConnection> remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server ordinarily closes the <xref:Microsoft.Data.SqlClient.SqlConnection>. However, the user can reopen the connection and continue.
An application that creates an instance of the <xref:Microsoft.Data.SqlClient.SqlConnection> object can require all direct and indirect callers to have sufficient permission to the code by setting declarative or imperative security demands. <xref:Microsoft.Data.SqlClient.SqlConnection> makes security demands using the <xref:Microsoft.Data.SqlClient.SqlClientPermission> object. Users can verify that their code has sufficient permissions by using the <xref:Microsoft.Data.SqlClient.SqlClientPermissionAttribute> object. Users and administrators can also use the [Caspol.exe (Code Access Security Policy Tool)](/dotnet/framework/tools/caspol-exe-code-access-security-policy-tool) to modify security policy at the machine, user, and enterprise levels. For more information, see [Security in .NET](/dotnet/standard/security/). For an example demonstrating how to use security demands, see [Code Access Security and ADO.NET](/dotnet/framework/data/adonet/code-access-security).
For more information about handling warning and informational messages from the server, see [Connection Events](/sql/connect/ado-net/connection-events). For more information about SQL Server engine errors and error messages, see [Database Engine Events and Errors](/sql/relational-databases/errors-events/database-engine-events-and-errors).
> [!CAUTION]
> You can force TCP instead of shared memory. You can do that by prefixing tcp: to the server name in the connection string or you can use localhost.
## Examples
The following example creates a <xref:Microsoft.Data.SqlClient.SqlCommand> and a <xref:Microsoft.Data.SqlClient.SqlConnection>. The <xref:Microsoft.Data.SqlClient.SqlConnection> is opened and set as the <xref:Microsoft.Data.SqlClient.SqlCommand.Connection%2A> for the <xref:Microsoft.Data.SqlClient.SqlCommand>. The example then calls <xref:Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery%2A>. To accomplish this, the <xref:Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery%2A> is passed a connection string and a query string that is a Transact-SQL INSERT statement. The connection is closed automatically when the code exits the using block.
[!code-csharp[SqlCommand_ExecuteNonQuery Example#1](~/../sqlclient/doc/samples/SqlCommand_ExecuteNonQuery.cs#1)]
]]></format>
</remarks>
</SqlConnection>
<ctor1>
<summary>Initializes a new instance of the <see cref="T:Microsoft.Data.SqlClient.SqlConnection" /> class.</summary>
</ctor1>
<ctor2>
<summary>Initializes a new instance of the <see cref="T:Microsoft.Data.SqlClient.SqlConnection" /> class.</summary>
<remarks>
<format type="text/markdown"><]
]]></format>
</remarks>
</ctor2>
<ctorConnectionString>
<param name="connectionString">The connection used to open the SQL Server database.</param>
<summary>Initializes a new instance of the <see cref="T:Microsoft.Data.SqlClient.SqlConnection" /> class when given a string that contains the connection string.</summary>
<remarks>
<format type="text/markdown"><]
]]></format>
</remarks>
<exception cref="T:System.ArgumentException">The supplied connection string argument failed <see cref="T:Microsoft.Data.SqlClient.SqlConnection.ConnectionString" /> validation.</exception>
</ctorConnectionString>
<ctorConnectionStringCredential>
<param name="connectionString">A connection string that does not use any of the following connection string keywords: <see langword="Integrated Security = true" />, <see langword="UserId" />, or <see langword="Password" />; or that does not use <see langword="ContextConnection = true" />.</param>
<param name="credential">A <see cref="T:Microsoft.Data.SqlClient.SqlCredential" /> object. If <paramref name="credential" /> is null, <see cref="M:Microsoft.Data.SqlClient.SqlConnection.#ctor(System.String,Microsoft.Data.SqlClient.SqlCredential)" /> is functionally equivalent to <see cref="M:Microsoft.Data.SqlClient.SqlConnection.#ctor(System.String)" />.</param>
<summary>Initializes a new instance of the <see cref="T:Microsoft.Data.SqlClient.SqlConnection" /> class given a connection string, that does not use <see langword="Integrated Security = true" /> and a <see cref="T:Microsoft.Data.SqlClient.SqlCredential" /> object that contains the user ID and password.</summary>
<remarks>To be added.</remarks>
<exception cref="T:System.ArgumentException">The supplied arguments failed validation, including <see cref="T:Microsoft.Data.SqlClient.SqlConnection.ConnectionString" /> validation.</exception>
</ctorConnectionStringCredential>
<AccessToken>
<summary>Gets or sets the access token for the connection.</summary>
<value>The access token for the connection.</value>
<remarks>To be added.</remarks>
</AccessToken>
<BeginDbTransaction>
<param name="isolationLevel">To be added.</param>
<summary>To be added.</summary>
<returns>To be added.</returns>
<remarks>To be added.</remarks>
</BeginDbTransaction>
<BeginTransaction1>
<summary>Starts a database transaction.</summary>
</BeginTransaction1>
<BeginTransaction2>
<summary>Starts a database transaction.</summary>
<returns>An object representing the new transaction.</returns>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
This command maps to the SQL Server implementation of BEGIN TRANSACTION.
You must explicitly commit or roll back the transaction using the <xref:Microsoft.Data.SqlClient.SqlTransaction.Commit%2A> or <xref:Microsoft.Data.SqlClient.SqlTransaction.Rollback%2A> method. To make sure that the .NET Framework Data Provider for SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.
> [!NOTE]
> If you do not specify an isolation level, the default isolation level is used. To specify an isolation level with the <xref:Microsoft.Data.SqlClient.SqlConnection.BeginTransaction%2A> method, use the overload that takes the `iso` parameter (<xref:Microsoft.Data.SqlClient.SqlConnection.BeginTransaction%2A>). The isolation level set for a transaction persists after the transaction is completed and until the connection is closed or disposed. Setting the isolation level to **Snapshot** in a database where the snapshot isolation level is not enabled does not throw an exception. The transaction will complete using the default isolation level.
> [!CAUTION]
> If a transaction is started and a level 16 or higher error occurs on the server, the transaction will not be rolled back until the <xref:Microsoft.Data.SqlClient.SqlDataReader.Read%2A> method is invoked. No exception is thrown on **ExecuteReader**.
> [!CAUTION]
> When your query returns a large amount of data and calls `BeginTransaction`, a <xref:Microsoft.Data.SqlClient.SqlException> is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.
For more information on SQL Server transactions, see [Transactions (Transact-SQL)](/sql/t-sql/language-elements/transactions-transact-sql).
## Examples
The following example creates a <xref:Microsoft.Data.SqlClient.SqlConnection> and a <xref:Microsoft.Data.SqlClient.SqlTransaction>. It also demonstrates how to use the <xref:Microsoft.Data.SqlClient.SqlConnection.BeginTransaction%2A>, a <xref:Microsoft.Data.SqlClient.SqlTransaction.Commit%2A>, and <xref:Microsoft.Data.SqlClient.SqlTransaction.Rollback%2A> methods.
[!code-csharp[SqlConnection_BeginTransaction Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction.cs#1)]
]]></format>
</remarks>
<exception cref="T:Microsoft.Data.SqlClient.SqlException">Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).</exception>
<exception cref="T:System.InvalidOperationException">Parallel transactions are not supported.</exception>
</BeginTransaction2>
<BeginTransactionIso>
<param name="iso">The isolation level under which the transaction should run.</param>
<summary>Starts a database transaction with the specified isolation level.</summary>
<returns>An object representing the new transaction.</returns>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
This command maps to the SQL Server implementation of BEGIN TRANSACTION.
You must explicitly commit or roll back the transaction using the <xref:Microsoft.Data.SqlClient.SqlTransaction.Commit%2A> or <xref:Microsoft.Data.SqlClient.SqlTransaction.Rollback%2A> method. To make sure that the .NET Framework Data Provider for SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.
> [!NOTE]
> After a transaction is committed or rolled back, the isolation level of the transaction persists for all subsequent commands that are in autocommit mode (the SQL Server default). This can produce unexpected results, such as an isolation level of REPEATABLE READ persisting and locking other users out of a row. To reset the isolation level to the default (READ COMMITTED), execute the Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED statement, or call <xref:Microsoft.Data.SqlClient.SqlConnection.BeginTransaction%2A?displayProperty=nameWithType> followed immediately by <xref:Microsoft.Data.SqlClient.SqlTransaction.Commit%2A?displayProperty=nameWithType>. For more information on SQL Server isolation levels, see [Transaction Isolation Levels](/sql/t-sql/language-elements/transaction-isolation-levels).
For more information on SQL Server transactions, see [Transactions (Transact-SQL)](/sql/t-sql/language-elements/transactions-transact-sql).
> [!CAUTION]
> When your query returns a large amount of data and calls `BeginTransaction`, a <xref:Microsoft.Data.SqlClient.SqlException> is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.
## Examples
The following example creates a <xref:Microsoft.Data.SqlClient.SqlConnection> and a <xref:Microsoft.Data.SqlClient.SqlTransaction>. It also demonstrates how to use the <xref:Microsoft.Data.SqlClient.SqlConnection.BeginTransaction%2A>, a <xref:Microsoft.Data.SqlClient.SqlTransaction.Commit%2A>, and <xref:Microsoft.Data.SqlClient.SqlTransaction.Rollback%2A> methods.
[!code-csharp[SqlConnection_BeginTransaction1 Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction1.cs#1)]
]]></format>
</remarks>
<exception cref="T:Microsoft.Data.SqlClient.SqlException">Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).</exception>
<exception cref="T:System.InvalidOperationException">Parallel transactions are not supported.</exception>
</BeginTransactionIso>
<BeginTransactionTransactionName>
<param name="transactionName">The name of the transaction.</param>
<summary>Starts a database transaction with the specified transaction name.</summary>
<returns>An object representing the new transaction.</returns>
<remarks>
<format type="text/markdown"><.
> [!CAUTION]
> When your query returns a large amount of data and calls `BeginTransaction`, a <xref:Microsoft.Data.SqlClient.SqlException> is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.
## Examples
The following example creates a <xref:Microsoft.Data.SqlClient.SqlConnection> and a <xref:Microsoft.Data.SqlClient.SqlTransaction>. It also demonstrates how to use the <xref:Microsoft.Data.SqlClient.SqlConnection.BeginTransaction%2A>, a <xref:Microsoft.Data.SqlClient.SqlTransaction.Commit%2A>, and <xref:Microsoft.Data.SqlClient.SqlTransaction.Rollback%2A> methods.
[!code-csharp[SqlConnection_BeginTransaction2 Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction2.cs#1)]
]]></format>
</remarks>
<exception cref="T:Microsoft.Data.SqlClient.SqlException">Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).</exception>
<exception cref="T:System.InvalidOperationException">Parallel transactions are not supported.</exception>
</BeginTransactionTransactionName>
<BeginTransactionIsoTransactionName>
<param name="iso">The isolation level under which the transaction should run.</param>
<param name="transactionName">The name of the transaction.</param>
<summary>Starts a database transaction with the specified isolation level and transaction name.</summary>
<returns>An object representing the new transaction.</returns>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
This command maps to the SQL Server implementation of BEGIN TRANSACTION.
The value in the `transactionName` parameter can be used in later calls to <xref:Microsoft.Data.SqlClient.SqlTransaction.Rollback%2A> and in the `savePoint` parameter of the <xref:Microsoft.Data.SqlClient.SqlTransaction.Save%2A> method.
You must explicitly commit or roll back the transaction using the <xref:Microsoft.Data.SqlClient.SqlTransaction.Commit%2A> or <xref:Microsoft.Data.SqlClient.SqlTransaction.Rollback%2A> method. To make sure that the SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.
> [!NOTE]
> After a transaction is committed or rolled back, the isolation level of the transaction persists for all subsequent commands that are in autocommit mode (the SQL Server default). This can produce unexpected results, such as an isolation level of REPEATABLE READ persisting and locking other users out of a row. To reset the isolation level to the default (READ COMMITTED), execute the Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED statement, or call <xref:Microsoft.Data.SqlClient.SqlConnection.BeginTransaction%2A?displayProperty=nameWithType> followed immediately by <xref:Microsoft.Data.SqlClient.SqlTransaction.Commit%2A?displayProperty=nameWithType>. For more information on SQL Server isolation levels, see [Transaction Isolation Levels](/sql/t-sql/language-elements/transaction-isolation-levels).
For more information on SQL Server transactions, see [Transactions (Transact-SQL)](/sql/t-sql/language-elements/transactions-transact-sql).
> [!CAUTION]
> When your query returns a large amount of data and calls `BeginTransaction`, a <xref:Microsoft.Data.SqlClient.SqlException> is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.
## Examples
The following example creates a <xref:Microsoft.Data.SqlClient.SqlConnection> and a <xref:Microsoft.Data.SqlClient.SqlTransaction>. It also demonstrates how to use the <xref:Microsoft.Data.SqlClient.SqlConnection.BeginTransaction%2A>, a <xref:Microsoft.Data.SqlClient.SqlTransaction.Commit%2A>, and <xref:Microsoft.Data.SqlClient.SqlTransaction.Rollback%2A> methods.
[!code-csharp[SqlConnection_BeginTransaction3 Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction3.cs#1)]
]]></format>
</remarks>
<exception cref="T:Microsoft.Data.SqlClient.SqlException">Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).</exception>
<exception cref="T:System.InvalidOperationException">Parallel transactions are not supported.</exception>
</BeginTransactionIsoTransactionName>
<ChangeDatabase>
<param name="database">The name of the database to use instead of the current database.</param>
<summary>Changes the current database for an open <see cref="T:Microsoft.Data.SqlClient.SqlConnection" />.</summary>
<remarks>
<format type="text/markdown"><]
]]></format>
</remarks>
<exception cref="T:System.ArgumentException">The database name is not valid.</exception>
<exception cref="T:System.InvalidOperationException">The connection is not open.</exception>
<exception cref="T:Microsoft.Data.SqlClient.SqlException">Cannot change the database.</exception>
</ChangeDatabase>
<ChangePassword>
<summary>Changes the SQL Server password.</summary>
</ChangePassword>
<ChangePasswordConnectionStringNewPassword>
<param name="connectionString">The connection string that contains enough information to connect to the server that you want. The connection string must contain the user ID and the current password.</param>
<param name="newPassword">The new password to set. This password must comply with any password security policy set on the server, including minimum length, requirements for specific characters, and so on.</param>
<summary>Changes the SQL Server password for the user indicated in the connection string to the supplied new password.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
When you are using SQL Server on Windows Server, developers can take advantage of functionality that lets the client application supply both the current and a new password in order to change the existing password. Applications can implement functionality such as prompting the user for a new password during initial login if the old one has expired, and this operation can be completed without administrator intervention.
The <xref:Microsoft.Data.SqlClient.SqlConnection.ChangePassword%2A> method changes the SQL Server password for the user indicated in the supplied `connectionString` parameter to the value supplied in the `newPassword` parameter. If the connection string includes the option for integrated security (that is, "Integrated Security=True" or the equivalent), an exception is thrown.
To determine that the password has expired, calling the <xref:Microsoft.Data.SqlClient.SqlConnection.Open%2A> method raises a <xref:Microsoft.Data.SqlClient.SqlException>. In order to indicate that the password that is contained within the connection string must be reset, the <xref:Microsoft.Data.SqlClient.SqlException.Number%2A> property for the exception contains the status value 18487 or 18488. The first value (18487) indicates that the password has expired and the second (18488) indicates that the password must be reset before logging in.
This method opens its own connection to the server, requests the password change, and closes the connection as soon as it has completed. This connection is not retrieved from, nor returned to, the SQL Server connection pool.
## Examples
The following is a simple example of changing a password:
```csharp
class Program {
static void Main(string[] args) {
Microsoft.Data.SqlClient.SqlConnection.ChangePassword(
"Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password",
"new_password");
}
}
```
```vb
Module Module1
Sub Main()
Microsoft.Data.SqlClient.SqlConnection.ChangePassword(
"Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password",
"new_password")
End Sub
End Module
```
The following console application demonstrates the issues involved in changing a user's password because the current password has expired.
[!code-csharp[SqlConnection_ConnectionString1#1](~/../sqlclient/doc/samples/SqlConnection_ConnectionString1.cs#1)]
]]></format>
</remarks>
<exception cref="T:System.ArgumentException">The connection string includes the option to use integrated security.
Or
The <paramref name="newPassword" /> exceeds 128 characters.</exception>
<exception cref="T:System.ArgumentNullException">Either the <paramref name="connectionString" /> or the <paramref name="newPassword" /> parameter is null.</exception>
</ChangePasswordConnectionStringNewPassword>
<ChangePasswordConnectionStringCredentialNewSecurePassword>
<param name="connectionString">The connection string that contains enough information to connect to a server. The connection string should not use any of the following connection string keywords: <see langword="Integrated Security = true" />, <see langword="UserId" />, or <see langword="Password" />; or <see langword="ContextConnection = true" />.</param>
<param name="credential">A <see cref="T:Microsoft.Data.SqlClient.SqlCredential" /> object.</param>
<param name="newSecurePassword">The new password. <paramref name="newSecurePassword" /> must be read only. The password must also comply with any password security policy set on the server (for example, minimum length and requirements for specific characters).</param>
<summary>Changes the SQL Server password for the user indicated in the <see cref="T:Microsoft.Data.SqlClient.SqlCredential" /> object.</summary>
<remarks>To be added.</remarks>
<exception cref="T:System.ArgumentException">
The connection string contains any combination of <see langword="UserId" />, <see langword="Password" />, or <see langword="Integrated Security=true" />.
-or-
<paramref name="newSecurePassword" /> is greater than 128 characters.
-or-
<paramref name="newSecurePassword" /> is not read only.
-or-
<paramref name="newSecurePassword" /> is an empty string.</exception>
<exception cref="T:System.ArgumentNullException">One of the parameters (<paramref name="connectionString" />, <paramref name="credential" />, or <paramref name="newSecurePassword" />) is null.</exception>
</ChangePasswordConnectionStringCredentialNewSecurePassword>
<ClearAllPools>
<summary>Empties the connection pool.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
<xref:Microsoft.Data.SqlClient.SqlConnection.ClearAllPools%2A> resets (or empties) the connection pool. If there are connections in use at the time of the call, they are marked appropriately and will be discarded (instead of being returned to the pool) when <xref:Microsoft.Data.SqlClient.SqlConnection.Close%2A> is called on them.
]]></format>
</remarks>
</ClearAllPools>
<ClearPool>
<param name="connection">The <see cref="T:Microsoft.Data.SqlClient.SqlConnection" /> to be cleared from the pool.</param>
<summary>Empties the connection pool associated with the specified connection.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
<xref:Microsoft.Data.SqlClient.SqlConnection.ClearPool%2A> clears the connection pool that is associated with the `connection`. If additional connections associated with `connection` are in use at the time of the call, they are marked appropriately and are discarded (instead of being returned to the pool) when <xref:Microsoft.Data.SqlClient.SqlConnection.Close%2A> is called on them.
]]></format>
</remarks>
</ClearPool>
<ClientConnectionId>
<summary>The connection ID of the most recent connection attempt, regardless of whether the attempt succeeded or failed.</summary>
<value>The connection ID of the most recent connection attempt.</value>
<remarks>
<format type="text/markdown"><) for certain connection errors. If the connection ID is not in the connection ring buffer, you can assume a network error.
]]></format>
</remarks>
</ClientConnectionId>
<Close>
<summary>Closes the connection to the database. This is the preferred method of closing any open connection.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
The <xref:Microsoft.Data.SqlClient.SqlConnection.Close%2A> method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if connection pooling is disabled.
> [!NOTE]
> Pending transactions started using Transact-SQL or <xref:Microsoft.Data.SqlClient.SqlConnection.BeginTransaction%2A> are automatically rolled back when the connection is reset if connection pooling is enabled. If connection pooling is off, the transaction is rolled back after `SqlConnection.Close` is called. Transactions started through <xref:System.Transactions> are controlled through the `System.Transactions` infrastructure, and are not affected by `SqlConnection.Close`.
An application can call <xref:Microsoft.Data.SqlClient.SqlConnection.Close%2A> more than one time. No exception is generated.
If the <xref:Microsoft.Data.SqlClient.SqlConnection> goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling `Close` or `Dispose`. `Close` and `Dispose` are functionally equivalent. If the connection pooling value `Pooling` is set to `true` or `yes`, the underlying connection is returned back to the connection pool. On the other hand, if `Pooling` is set to `false` or `no`, the underlying connection to the server is closed.
> [!NOTE]
> Login and logout events will not be raised on the server when a connection is fetched from or returned to the connection pool, because the connection is not actually closed when it is returned to the connection pool. For more information, see [SQL Server Connection Pooling (ADO.NET)](/sql/connect/ado-net/sql-server-connection-pooling).
> [!CAUTION]
> Do not call `Close` or `Dispose` on a Connection, a DataReader, or any other managed object in the `Finalize` method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a `Finalize` method in your class definition. For more information, see [Garbage Collection](/dotnet/standard/garbage-collection/).
## Examples
The following example creates a <xref:Microsoft.Data.SqlClient.SqlConnection>, opens it, displays some of its properties. The connection is automatically closed at the end of the `using` block.
[!code-csharp[SqlConnection_Open Example#1](~/../sqlclient/doc/samples/SqlConnection_Open.cs#1)]
]]></format>
</remarks>
<exception cref="T:Microsoft.Data.SqlClient.SqlException">The connection-level error that occurred while opening the connection.</exception>
</Close>
<ColumnEncryptionKeyCacheTtl>
<summary>Gets or sets the time-to-live for column encryption key entries in the column encryption key cache for the <see href="https://docs.microsoft.com/sql/relational-databases/security/encryption/always-encrypted-database-engine">Always Encrypted</see> feature. The default value is 2 hours. 0 means no caching at all.</summary>
<value>The time interval.</value>
<remarks>To be added.</remarks>
</ColumnEncryptionKeyCacheTtl>
<ColumnEncryptionQueryMetadataCacheEnabled>
<summary>Gets or sets a value that indicates whether query metadata caching is enabled (true) or not (false) for parameterized queries running against <see href="https://docs.microsoft.com/sql/relational-databases/security/encryption/always-encrypted-database-engine">Always Encrypted</see> enabled databases. The default value is true.</summary>
<value>Returns true if query metadata caching is enabled; otherwise false. true is the default.</value>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
For parameterized queries, SqlClient makes a roundtrip to SQL Server for parameter metadata, to see which parameter it needs to encrypt and how (which keys and algorithms should be used). If the application calls the same query multiple times, an extra roundtrip is made to the server each time, which degrades application performance.
With **ColumnEncryptionQueryMetadataCacheEnabled** set to true, if the same query is called multiple times, the roundtrip to the server will be made only once. The cache has a non-configurable Max size parameter that is set to 2000 queries.
]]></format>
</remarks>
</ColumnEncryptionQueryMetadataCacheEnabled>
<ColumnEncryptionTrustedMasterKeyPaths>
<summary>Allows you to set a list of trusted key paths for a database server. If while processing an application query the driver receives a key path that is not on the list, the query will fail. This property provides additional protection against security attacks that involve a compromised SQL Server providing fake key paths, which may lead to leaking key store credentials.</summary>
<value>The list of trusted master key paths for the column encryption.</value>
<remarks>To be added.</remarks>
</ColumnEncryptionTrustedMasterKeyPaths>
<CommandTimeout>
<summary>
Gets the default wait time (in seconds) before terminating the attempt to execute a command and generating an error. The default is 30 seconds.
</summary>
<value>
The time in seconds to wait for the command to execute. The default is 30 seconds.
</value>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
You can set the default wait time by using the `Command Timeout` keyword in the connection string. A value of 0 indicates no limit (an attempt to execute a command will wait indefinitely).
]]></format>
</remarks>
</CommandTimeout>
<ConnectionString>
<summary>Gets or sets the string used to open a SQL Server database.</summary>
<value>The connection string that includes the source database name, and other parameters needed to establish the initial connection. The default value is an empty string.</value>
<remarks>
<format type="text/markdown">
<.
The <xref:Microsoft.Data.SqlClient.SqlConnection.ConnectionString%2A> property can be set only when the connection is closed. Many of the connection string values have corresponding read-only properties. When the connection string is set, these properties are updated, except when an error is detected. In this case, none of the properties are updated. <xref:Microsoft.Data.SqlClient.SqlConnection> properties return only those settings that are contained in the <xref:Microsoft.Data.SqlClient.SqlConnection.ConnectionString%2A>.
To connect to a local computer, specify "(local)" for the server. If a server name is not specified, a connection will be attempted to the default instance on the local computer.
Resetting the <xref:Microsoft.Data.SqlClient.SqlConnection.ConnectionString%2A> on a closed connection resets all connection string values (and related properties) including the password. For example, if you set a connection string that includes "Database= AdventureWorks", and then reset the connection string to "Data Source=myserver;Integrated Security=true", the <xref:Microsoft.Data.SqlClient.SqlConnection.Database%2A> property is no longer set to "AdventureWorks".
The connection string is parsed immediately after being set. If errors in syntax are found when parsing, a runtime exception, such as <xref:System.ArgumentException>, is generated. Other errors can be found only when an attempt is made to open the connection.
The basic format of a connection string includes a series of keyword/value pairs separated by semicolons. The equal sign (=) connects each keyword and its value. To include values that contain a semicolon, single-quote character, or double-quote character, the value must be enclosed in double quotation marks. If the value contains both a semicolon and a double-quote character, the value can be enclosed in single quotation marks. The single quotation mark is also useful if the value starts with a double-quote character. Conversely, the double quotation mark can be used if the value starts with a single quotation mark. If the value contains both single-quote and double-quote characters, the quotation mark character used to enclose the value must be doubled every time it occurs within the value.
To include preceding or trailing spaces in the string value, the value must be enclosed in either single quotation marks or double quotation marks. Any leading or trailing spaces around integer, Boolean, or enumerated values are ignored, even if enclosed in quotation marks. However, spaces within a string literal keyword or value are preserved. Single or double quotation marks may be used within a connection string without using delimiters (for example, Data Source= my'Server or Data Source= my"Server), unless a quotation mark character is the first or last character in the value.
Keywords are not case sensitive.
The following table lists the valid names for keyword values within the <xref:Microsoft.Data.SqlClient.SqlConnection.ConnectionString%2A>.
|Keyword|Default|Description|
|-------------|-------------|-----------------|
|Addr|N/A|Synonym of **Data Source**.|
|Address|N/A|Synonym of **Data Source**.|
|App|N/A|Synonym of **Application Name**.|
|Application Intent<br /><br /> -or-<br /><br />ApplicationIntent|ReadWrite|Declares the application workload type when connecting to a server. Possible values are `ReadOnly` and `ReadWrite`. For example:<br /><br /> `ApplicationIntent=ReadOnly`<br /><br /> For more information about SqlClient support for Always On Availability Groups, see [SqlClient Support for High Availability, Disaster Recovery](/sql/connect/ado-net/sql/sqlclient-support-high-availability-disaster-recovery).|
|Application Name|N/A|The name of the application. If no application name is provided, 'Framework Microsoft SqlClient Data Provider' when running on .NET Framework and 'Core Microsoft SqlClient Data Provider' otherwise.<br /><br /> An application name can be 128 characters or less.|
|AttachDBFilename<br /><br /> -or-<br /><br /> Extended Properties<br /><br /> -or-<br /><br /> Initial File Name|N/A|The name of the primary database file, including the full path name of an attachable database. AttachDBFilename is only supported for primary data files with an .mdf extension.<br /><br /> If the value of the AttachDBFileName key is specified in the connection string, the database is attached and becomes the default database for the connection.<br /><br /> If this key is not specified and if the database was previously attached, the database will not be reattached. The previously attached database will be used as the default database for the connection.<br /><br /> If this key is specified together with the AttachDBFileName key, the value of this key will be used as the alias. However, if the name is already used in another attached database, the connection will fail.<br /><br /> The path may be absolute or relative by using the DataDirectory substitution string. If DataDirectory is used, the database file must exist within a subdirectory of the directory pointed to by the substitution string. **Note:** Remote server, HTTP, and UNC path names are not supported. <br /><br /> The database name must be specified with the keyword 'database' (or one of its aliases) as in the following:<br /><br /> <code>"AttachDbFileName=|DataDirectory|\data\YourDB.mdf;integrated security=true;database=YourDatabase"</code><br /><br /> An error will be generated if a log file exists in the same directory as the data file and the 'database' keyword is used when attaching the primary data file. In this case, remove the log file. Once the database is attached, a new log file will be automatically generated based on the physical path.|
|Attestation Protocol|NotSpecified|Gets or sets the value of Attestation Protocol.<br /><br />When no value is specified, secure enclaves are disabled on the connection.<br /><br />Valid values are:<br />`AAS`<br />`HGS`<br />`None` (Only valid in v3.1 and v4.1+))|
|Authentication|N/A|The authentication method used for [Connecting to SQL Database By Using Azure Active Directory Authentication](https://azure.microsoft.com/documentation/articles/sql-database-aad-authentication/#7-connect-to-your-database-by-using-azure-active-directory-identities).<br /><br /> Valid values are:<br /><br /> `Active Directory Integrated`, `Active Directory Interactive`, `Active Directory Password`, `Active Directory Service Principal`, `Active Directory Device Code Flow`, `Active Directory Managed Identity`, `Active Directory MSI`, `Active Directory Default`, `Sql Password`.|
|Column Encryption Setting|disabled|Enables or disables [Always Encrypted](/sql/relational-databases/security/encryption/always-encrypted-database-engine) functionality for the connection. Supported values are: `enabled` and `disabled`|
|Command Timeout|30|The default wait time (in seconds) before terminating the attempt to execute a command and generating an error.<br /><br /> Valid values are greater than or equal to 0 and less than or equal to 2147483647.|
|Connect Retry Count<br /><br /> -or-<br /><br />ConnectRetryCount|1|Controls the number of reconnection attempts after the client identifies an idle connection failure. Valid values are 0 to 255. The default is 1. 0 means do not attempt to reconnect (disable connection resiliency).<br /><br /> For additional information about idle connection resiliency, see [Technical Article - Idle Connection Resiliency](https://go.microsoft.com/fwlink/?LinkId=393996).|
|Connect Retry Interval<br /><br /> -or-<br /><br />ConnectRetryInterval|10|Specifies the time between each connection retry attempt (`ConnectRetryCount`). Valid values are 1 to 60 seconds (default=10), applied after the first reconnection attempt. When a broken connection is detected, the client immediately attempts to reconnect; this is the first reconnection attempt and only occurs if `ConnectRetryCount` is greater than 0. If the first reconnection attempt fails and `ConnectRetryCount` is greater than 1, the client waits `ConnectRetryInterval` to try the second and subsequent reconnection attempts.<br /><br /> For additional information about idle connection resiliency, see [Technical Article - Idle Connection Resiliency](https://go.microsoft.com/fwlink/?LinkId=393996).|
|Connect Timeout<br /><br /> -or-<br /><br /> Connection Timeout<br /><br /> -or-<br /><br /> Timeout|15|The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.<br /><br /> Valid values are greater than or equal to 0 and less than or equal to 2147483647.<br /><br /> When opening a connection to a Azure SQL Database, set the connection timeout to 30 seconds.|
|Current Language<br /><br /> -or-<br /><br /> Language|N/A|Sets the language used for database server warning or error messages.<br /><br /> The language name can be 128 characters or less.|
|Data Source<br /><br /> -or-<br /><br /> Server<br /><br /> -or-<br /><br /> Address<br /><br /> -or-<br /><br /> Addr<br /><br /> -or-<br /><br /> Network Address|N/A|The name or network address of the instance of SQL Server to which to connect. The port number can be specified after the server name:<br /><br /> `server=tcp:servername, portnumber`<br /><br /> When specifying a local instance, always use (local). To force a protocol, add one of the following prefixes:<br /><br /> `np:(local), tcp:(local), lpc:(local)`<br /><br /> You can also connect to a LocalDB database as follows:<br /><br /> `server=(localdb)\\myInstance`<br /><br /> For more information about LocalDB, see [SqlClient Support for LocalDB](/sql/connect/ado-net/sql/sqlclient-support-localdb).<br /><br /> **Data Source** must use the TCP format or the Named Pipes format.<br /><br /> TCP format is as follows:<br /><br /> - tcp:\<host name>\\<instance name\><br />- tcp:\<host name>,\<TCP/IP port number><br /><br /> The TCP format must start with the prefix "tcp:" and is followed by the database instance, as specified by a host name and an instance name. This format is not applicable when connecting to Azure SQL Database. TCP is automatically selected for connections to Azure SQL Database when no protocol is specified.<br /><br /> The host name MUST be specified in one of the following ways:<br /><br /> - NetBIOSName<br />- IPv4Address<br />- IPv6Address<br /><br /> The instance name is used to resolve to a particular TCP/IP port number on which a database instance is hosted. Alternatively, specifying a TCP/IP port number directly is also allowed. If both instance name and port number are not present, the default database instance is used.<br /><br /> The Named Pipes format is as follows:<br /><br /> - np:\\\\<host name\>\pipe\\<pipe name\><br /><br /> The Named Pipes format MUST start with the prefix "np:" and is followed by a named pipe name.<br /><br /> The host name MUST be specified in one of the following ways:<br /><br /> - NetBIOSName<br />- IPv4Address<br />- IPv6Address<br /><br /> The pipe name is used to identify the database instance to which the .NET application will connect.<br /><br /> If the value of the **Network** key is specified, the prefixes "tcp:" and "np:" should not be specified. **Note:** You can force the use of TCP instead of shared memory, either by prefixing **tcp:** to the server name in the connection string, or by using **localhost**.|
|Enclave Attestation Url|N/A|Gets or sets the enclave attestation URL to be used with enclave based Always Encrypted.|
|Encrypt|'true' in 4.0 and above<br/><br/>'false' in 3.x and below|Recognized values are:<br/>versions 1 - 4: `true`/`yes` and `false`/`no`<br/>versions 5+: `true`/`yes`/`mandatory`, `false`/`no`/`optional` and `strict`. When `true`, TLS encryption is used for all data sent between the client and server if the server has a certificate installed. When `strict`, TDS 8.0 TLS encryption is used and the `TrustServerCertificate` setting is ignored and treated as false. For more information, see [Connection String Syntax](/sql/connect/ado-net/connection-string-syntax).<br /><br /> When `Encrypt` is true or strict and `TrustServerCertificate` is false, the server name (or IP address) in a server's certificate must exactly match the server name (or IP address) specified in the connection string. Otherwise, the connection attempt will fail. For information about support for certificates whose subject starts with a wildcard character (*), see [Accepted wildcards used by server certificates for server authentication](https://support.microsoft.com/kb/258858).|
|Enlist|'true'|`true` indicates that the SQL Server connection pooler automatically enlists the connection in the creation thread's current transaction context.|
|Failover Partner|N/A|The name of the failover partner server where database mirroring is configured.<br /><br /> If the value of this key is "", then **Initial Catalog** must be present, and its value must not be "".<br /><br /> The server name can be 128 characters or less.<br /><br /> If you specify a failover partner but the failover partner server is not configured for database mirroring and the primary server (specified with the Server keyword) is not available, then the connection will fail.<br /><br /> If you specify a failover partner and the primary server is not configured for database mirroring, the connection to the primary server (specified with the Server keyword) will succeed if the primary server is available.|
|Failover Partner SPN<br /><br /> -or-<br /><br /> FailoverPartnerSPN|N/A|The SPN for the failover partner. The default value is an empty string, which causes SqlClient to use the default, driver-generated SPN.<br /><br /> (Only available in v5.0+)|
|Host Name In Certificate<br /><br /> -or-<br /><br />HostNameInCertificate|N/A|Available starting in version 5.0.<br/><br/>The host name to use when validating the server certificate. When not specified, the server name from the Data Source is used for certificate validation.|
|Initial Catalog<br /><br /> -or-<br /><br /> Database|N/A|The name of the database.<br /><br /> The database name can be 128 characters or less.|
|Integrated Security<br /><br /> -or-<br /><br /> Trusted_Connection|'false'|When `false`, User ID and Password are specified in the connection. When `true`, the current Windows account credentials are used for authentication.<br /><br /> Recognized values are `true`, `false`, `yes`, `no`, and `sspi` (strongly recommended), which is equivalent to `true`.<br /><br /> If User ID and Password are specified and Integrated Security is set to true, the User ID and Password will be ignored and Integrated Security will be used.<br /><br /> <xref:Microsoft.Data.SqlClient.SqlCredential> is a more secure way to specify credentials for a connection that uses SQL Server Authentication (`Integrated Security=false`).|
|IP Address Preference<br /><br /> -or-<br /><br /> IPAddressPreference|IPv4First|The IP address family preference when establishing TCP connections. If `Transparent Network IP Resolution` (in .NET Framework) or `Multi Subnet Failover` is set to true, this setting has no effect. Supported values include:<br /><br /> `IPAddressPreference=IPv4First`<br /><br />`IPAddressPreference=IPv6First`<br /><br />`IPAddressPreference=UsePlatformDefault`|
|Load Balance Timeout<br /><br /> -or-<br /><br /> Connection Lifetime|0|When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by `Connection Lifetime`. This is useful in clustered configurations to force load balancing between a running server and a server just brought online.<br /><br /> A value of zero (0) causes pooled connections to have the maximum connection timeout.|
|Max Pool Size|100|The maximum number of connections that are allowed in the pool.<br /><br /> Valid values are greater than or equal to 1. Values that are less than **Min Pool Size** generate an error.|
|Min Pool Size|0|The minimum number of connections that are allowed in the pool.<br /><br /> Valid values are greater than or equal to 0. Zero (0) in this field means no minimum connections are initially opened.<br /><br /> Values that are greater than **Max Pool Size** generate an error.|
|Multiple Active Result Sets<br /><br /> -or-<br /><br />MultipleActiveResultSets|false|When `true`, an application can maintain multiple active result sets (MARS). When `false`, an application must process or cancel all result sets from one batch before it can execute any other batch on that connection.<br /><br /> Recognized values are `true` and `false`.<br /><br /> For more information, see [Multiple Active Result Sets (MARS)](/sql/connect/ado-net/sql/multiple-active-result-sets-mars).|
|Multi Subnet Failover<br /><br /> -or-<br /><br />MultiSubnetFailover|false|Always specify `multiSubnetFailover=True` when connecting to the availability group listener of a SQL Server 2012 (or later) availability group or a SQL Server 2012 (or later) Failover Cluster Instance. `multiSubnetFailover=True` configures SqlClient to provide faster detection of and connection to the (currently) active server. Possible values are `Yes` and `No`, `True` and `False` or `1` and `0`. For example:<br /><br /> `MultiSubnetFailover=True`<br /><br /> The default is `False`. For more information about SqlClient's support for Always On AGs, see [SqlClient Support for High Availability, Disaster Recovery](/sql/connect/ado-net/sql/sqlclient-support-high-availability-disaster-recovery).|
|Network Library<br /><br /> -or-<br /><br /> Network<br /><br /> -or-<br /><br /> Net|N/A|The network library used to establish a connection to an instance of SQL Server. Supported values include:<br /><br /> dbnmpntw (Named Pipes)<br /><br /> dbmsrpcn (Multiprotocol, Windows RPC)<br /><br /> dbmsadsn (Apple Talk)<br /><br /> dbmsgnet (VIA)<br /><br /> dbmslpcn (Shared Memory)<br /><br /> dbmsspxn (IPX/SPX)<br /><br /> dbmssocn (TCP/IP)<br /><br /> Dbmsvinn (Banyan Vines)<br /><br /> The corresponding network DLL must be installed on the system to which you connect. If you do not specify a network and you use a local server (for example, "." or "(local)"), shared memory is used. In this example, the network library is Win32 Winsock TCP/IP (dbmssocn), and 1433 is the port being used.<br /><br /> `Network Library=dbmssocn;Data Source=000.000.000.000,1433;`|
|Packet Size|8000|Size in bytes of the network packets used to communicate with an instance of SQL Server.<br /><br /> The packet size can be greater than or equal to 512 and less than or equal to 32768.|
|Password<br /><br /> -or-<br /><br /> PWD|N/A|The password for the SQL Server account logging on. Not recommended. To maintain a high level of security, we strongly recommend that you use the `Integrated Security` or `Trusted_Connection` keyword instead. <xref:Microsoft.Data.SqlClient.SqlCredential> is a more secure way to specify credentials for a connection that uses SQL Server Authentication.<br /><br /> The password must be 128 characters or less.|
|Persist Security Info<br /><br /> -or-<br /><br /> PersistSecurityInfo|'false'|When set to `false` or `no` (strongly recommended), security-sensitive information, such as the password or access token, is not returned as part of the connection if the connection is open or has ever been in an open state. This property should only be set to `true` if your application has a specific need to read the password out of an already-opened database connection. The default value of `false` is the more secure setting; using `true` for this property opens your application to security risks such as accidentally logging or tracing the database password.<br /><br />Resetting the connection string resets all connection string values including the password. Recognized values are `true`, `false`, `yes`, and `no`.|
|Pool Blocking Period<br /><br /> -or-<br /><br />PoolBlockingPeriod|Auto|Sets the blocking period behavior for a connection pool. See <xref:Microsoft.Data.SqlClient.SqlConnectionStringBuilder.PoolBlockingPeriod> property for details.|
|Pooling|'true'|When the value of this key is set to true, any newly created connection will be added to the pool when closed by the application. In a next attempt to open the same connection, that connection will be drawn from the pool.<br /><br /> Connections are considered the same if they have the same connection string. Different connections have different connection strings.<br /><br /> The value of this key can be "true", "false", "yes", or "no".|
|Replication|'false'|`true` if replication is supported using the connection.|
|Server SPN<br /><br /> -or-<br /><br /> ServerSPN|N/A|The SPN for the data source. The default value is an empty string, which causes SqlClient to use the default, driver-generated SPN.<br /><br /> (Only available in v5.0+)|
|Transaction Binding|Implicit Unbind|Controls connection association with an enlisted `System.Transactions` transaction.<br /><br /> Possible values are:<br /><br /> `Transaction Binding=Implicit Unbind;`<br /><br /> `Transaction Binding=Explicit Unbind;`<br /><br /> Implicit Unbind causes the connection to detach from the transaction when it ends. After detaching, additional requests on the connection are performed in autocommit mode. The `System.Transactions.Transaction.Current` property is not checked when executing requests while the transaction is active. After the transaction has ended, additional requests are performed in autocommit mode.<br /><br /> If the system ends the transaction (in the scope of a using block) before the last command completes, it will throw <xref:System.InvalidOperationException>.<br /><br /> Explicit Unbind causes the connection to remain attached to the transaction until the connection is closed or an explicit `SqlConnection.TransactionEnlist(null)` is called. Beginning in .NET Framework 4.0, changes to Implicit Unbind make Explicit Unbind obsolete. An `InvalidOperationException` is thrown if `Transaction.Current` is not the enlisted transaction or if the enlisted transaction is not active.|
|Transparent Network IP Resolution<br /><br /> -or-<br /><br />TransparentNetworkIPResolution|See description.|When the value of this key is set to `true`, the application is required to retrieve all IP addresses for a particular DNS entry and attempt to connect with the first one in the list. If the connection is not established within 0.5 seconds, the application will try to connect to all others in parallel. When the first answers, the application will establish the connection with the respondent IP address.<br /><br /> If the `MultiSubnetFailover` key is set to `true`, `TransparentNetworkIPResolution` is ignored.<br /><br /> If the `Failover Partner` key is set, `TransparentNetworkIPResolution` is ignored.<br /><br /> The value of this key must be `true`, `false`, `yes`, or `no`.<br /><br /> A value of `yes` is treated the same as a value of `true`.<br /><br /> A value of `no` is treated the same as a value of `false`.<br /><br /> The default values are as follows:<br /><br /> <ul><li>`false` when:<br /><br /> <ul><li>Connecting to Azure SQL Database where the data source ends with:<br /><br /> <ul><li>.database.chinacloudapi.cn</li><li>.database.usgovcloudapi.net</li><li>.database.cloudapi.de</li><li>.database.windows.net</li></ul></li><li>`Authentication` is 'Active Directory Password' or 'Active Directory Integrated'</li></ul></li><li>`true` in all other cases.</li></ul>|
|Trust Server Certificate<br /><br /> -or-<br /><br />TrustServerCertificate|'false'|When set to `true`, TLS is used to encrypt the channel when bypassing walking the certificate chain to validate trust. If TrustServerCertificate is set to `true` and Encrypt is set to `false`, the channel is not encrypted. Recognized values are `true`, `false`, `yes`, and `no`. For more information, see [Connection String Syntax](/sql/connect/ado-net/connection-string-syntax).|
|Type System Version|N/A|A string value that indicates the type system the application expects. The functionality available to a client application is dependent on the version of SQL Server and the compatibility level of the database. Explicitly setting the type system version that the client application was written for avoids potential problems that could cause an application to break if a different version of SQL Server is used. **Note:** The type system version cannot be set for common language runtime (CLR) code executing in-process in SQL Server. For more information, see [SQL Server Common Language Runtime Integration](/dotnet/framework/data/adonet/sql/sql-server-common-language-runtime-integration). <br /><br /> Possible values are:<br /><br /> `Type System Version=SQL Server 2012;`<br /><br /> `Type System Version=SQL Server 2008;`<br /><br /> `Type System Version=SQL Server 2005;`<br /><br /> `Type System Version=Latest;`<br /><br /> `Type System Version=SQL Server 2012;` specifies that the application will require version 11.0.0.0 of Microsoft.SqlServer.Types.dll. The other `Type System Version` settings will require version 10.0.0.0 of Microsoft.SqlServer.Types.dll.<br /><br /> `Latest` is obsolete and should not be used. `Latest` is equivalent to `Type System Version=SQL Server 2008;`.|
|User ID<br /><br /> -or-<br /><br /> UID<br /><br /> -or-<br /><br /> User|N/A|The SQL Server login account. Not recommended. To maintain a high level of security, we strongly recommend that you use the `Integrated Security` or `Trusted_Connection` keywords instead. <xref:Microsoft.Data.SqlClient.SqlCredential> is a more secure way to specify credentials for a connection that uses SQL Server Authentication.<br /><br /> The user ID must be 128 characters or less.|
|User Instance|'false'|A value that indicates whether to redirect the connection from the default SQL Server Express instance to a runtime-initiated instance running under the account of the caller.|
|Workstation ID<br /><br /> -or-<br /><br /> WSID|The local computer name|The name of the workstation connecting to SQL Server.<br /><br /> The ID must be 128 characters or less.|
The following list contains the valid names for connection pooling values within the <xref:Microsoft.Data.SqlClient.SqlConnection.ConnectionString%2A>. For more information, see [SQL Server Connection Pooling (ADO.NET)](/sql/connect/ado-net/sql-server-connection-pooling).
- Connection Lifetime (or Load Balance Timeout)
- Enlist
- Max Pool Size
- Min Pool Size
- Pooling
When you are setting keyword or connection pooling values that require a Boolean value, you can use 'yes' instead of 'true', and 'no' instead of 'false'. Integer values are represented as strings.
> [!NOTE]
> The .NET Framework Data Provider for SQL Server uses its own protocol to communicate with SQL Server. Therefore, it does not support the use of an ODBC data source name (DSN) when connecting to SQL Server because it does not add an ODBC layer.
> [!NOTE]
> Universal data link (UDL) files are not supported for the .NET Framework Data Provider for SQL Server.
> [!CAUTION]
> In this release, the application should use caution when constructing a connection string based on user input (for example when retrieving user ID and password information from a dialog box, and appending it to the connection string). The application should make sure that a user cannot embed additional connection string parameters in these values (for example, entering a password as "validpassword;database=somedb" in an attempt to attach to a different database). If you need to construct connection strings based on user input, use the new <xref:Microsoft.Data.SqlClient.SqlConnectionStringBuilder>, which validates the connection string and helps to eliminate this problem. See [Connection String Builders](/sql/connect/ado-net/connection-string-builders) for more information.
## Examples
The following example creates a <xref:Microsoft.Data.SqlClient.SqlConnection> and sets the <xref:Microsoft.Data.SqlClient.SqlConnection.ConnectionString%2A> property before opening the connection.
[!code-csharp[SqlConnection_ConnectionString Example#1](~/../sqlclient/doc/samples/SqlConnection_ConnectionString.cs#1)]
]]></format>
</remarks>
<exception cref="T:System.ArgumentException">An invalid connection string argument has been supplied, or a required connection string argument has not been supplied.</exception>
</ConnectionString>
<ConnectionTimeout>
<summary>Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error.</summary>
<value>The time (in seconds) to wait for a connection to open. The default value is 15 seconds.</value>
<remarks>
<format type="text/markdown"><]
]]></format>
</remarks>
<exception cref="T:System.ArgumentException">The value set is less than 0.</exception>
</ConnectionTimeout>
<CreateCommand>
<summary>Creates and returns a <see cref="T:Microsoft.Data.SqlClient.SqlCommand" /> object associated with the <see cref="T:Microsoft.Data.SqlClient.SqlConnection" />.</summary>
<returns>A <see cref="T:Microsoft.Data.SqlClient.SqlCommand" /> object.</returns>
<remarks>
<format type="text/markdown"><]
]]></format>
</remarks>
</CreateCommand>
<CreateDbCommand>
<summary>To be added.</summary>
<returns>To be added.</returns>
<remarks>To be added.</remarks>
</CreateDbCommand>
<Credential>
<summary>Gets or sets the <see cref="T:Microsoft.Data.SqlClient.SqlCredential" /> object for this connection.</summary>
<value>The <see cref="T:Microsoft.Data.SqlClient.SqlCredential" /> object for this connection.</value>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
`Persist Security Info = true` is required to get the value of the <xref:Microsoft.Data.SqlClient.SqlCredential> object with <xref:Microsoft.Data.SqlClient.SqlConnection.Credential%2A>.
The default value of <xref:Microsoft.Data.SqlClient.SqlConnection.Credential%2A> is null.
An <xref:System.InvalidOperationException> exception will be raised:
- If <xref:Microsoft.Data.SqlClient.SqlConnection.Credential%2A> is set on an open connection.
- If <xref:Microsoft.Data.SqlClient.SqlConnection.Credential%2A> is set when `Integrated Security = true`.
- If <xref:Microsoft.Data.SqlClient.SqlConnection.Credential%2A> is set when the connection string uses `Password`.
- If <xref:Microsoft.Data.SqlClient.SqlConnection.Credential%2A> is set when the connection string uses `UserID`.
]]></format>
</remarks>
</Credential>
<Credentials>
<summary>To be added.</summary>
<value>To be added.</value>
<remarks>To be added.</remarks>
</Credentials>
<Database>
<summary>Gets the name of the current database or the database to be used after a connection is opened.</summary>
<value>The name of the current database or the name of the database to be used after a connection is opened. The default value is an empty string.</value>
<remarks>
<format type="text/markdown"><]
]]></format>
</remarks>
</Database>
<DataSource>
<summary>Gets the name of the instance of SQL Server to which to connect.</summary>
<value>The name of the instance of SQL Server to which to connect. The default value is an empty string.</value>
<remarks>
<format type="text/markdown"><]
]]></format>
</remarks>
</DataSource>
<DbProviderFactory>
<summary>To be added.</summary>
<value>To be added.</value>
<remarks>To be added.</remarks>
</DbProviderFactory>
<Dispose>
<param name="disposing">To be added.</param>
<summary>To be added.</summary>
<remarks>To be added.</remarks>
</Dispose>
<EnlistDistributedTransaction>
<param name="transaction">A reference to an existing <see cref="T:System.EnterpriseServices.ITransaction" /> in which to enlist.</param>
<summary>Enlists in the specified transaction as a distributed transaction.</summary>
<remarks>
<format type="text/markdown"><.
You can continue to enlist in an existing distributed transaction using the **EnlistDistributedTransaction** method if auto-enlistment is disabled. Enlisting in an existing distributed transaction makes sure that, if the transaction is committed or rolled back, modifications made by the code at the data source are also committed or rolled back.
`EnlistDistributedTransaction` returns an exception if the <xref:Microsoft.Data.SqlClient.SqlConnection> has already started a transaction using <xref:Microsoft.Data.SqlClient.SqlConnection.BeginTransaction%2A>. However, if the transaction is a local transaction started at the data source (for example, by explicitly executing the BEGIN TRANSACTION statement using an <xref:Microsoft.Data.SqlClient.SqlCommand> object), **EnlistDistributedTransaction** rolls back the local transaction and enlists in the existing distributed transaction as requested. You do not receive notice that the local transaction was rolled back, and are responsible for managing any local transactions not started using <xref:Microsoft.Data.SqlClient.SqlConnection.BeginTransaction%2A>.
]]></format>
</remarks>
</EnlistDistributedTransaction>
<EnlistTransaction>
<param name="transaction">A reference to an existing <see cref="T:System.Transactions.Transaction" /> in which to enlist.</param>
<summary>Enlists in the specified transaction as a distributed transaction.</summary>
<remarks>
<format type="text/markdown"><.
]]></format>
</remarks>
</EnlistTransaction>
<FireInfoMessageEventOnUserErrors>
<summary>Gets or sets the <see cref="P:Microsoft.Data.SqlClient.SqlConnection.FireInfoMessageEventOnUserErrors" /> property.</summary>
<value>
<see langword="true" /> if the <see cref="P:Microsoft.Data.SqlClient.SqlConnection.FireInfoMessageEventOnUserErrors" /> property has been set; otherwise <see langword="false" />.</value>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
When you set <xref:Microsoft.Data.SqlClient.SqlConnection.FireInfoMessageEventOnUserErrors%2A> to `true`, errors that were previously treated as exceptions are now handled as <xref:Microsoft.Data.SqlClient.SqlConnection.InfoMessage> events. All events fire immediately and are handled by the event handler. If is <xref:Microsoft.Data.SqlClient.SqlConnection.FireInfoMessageEventOnUserErrors%2A> is set to `false`, then <xref:Microsoft.Data.SqlClient.SqlConnection.InfoMessage> events are handled at the end of the procedure.
> [!NOTE]
> An error with a severity level of 17 or above that causes the server to stop processing the command needs to be handled as an exception. In this case, an exception is thrown regardless of how the error is handled in the <xref:Microsoft.Data.SqlClient.SqlConnection.InfoMessage> event.
For more information on working with events, see [Connection Events](/sql/connect/ado-net/connection-events). For more information on errors generated by the SQL Server engine, see [Database Engine Errors](/sql/relational-databases/errors-events/database-engine-events-and-errors).
]]></format>
</remarks>
</FireInfoMessageEventOnUserErrors>
<GetSchema1>
<summary>Returns schema information for the data source of this <see cref="T:Microsoft.Data.SqlClient.SqlConnection" />.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
If you attempt to retrieve schema information for more than one versioned stored procedure, the schema for the latest one only is returned.
]]></format>
</remarks>
</GetSchema1>
<GetSchema2>
<summary>Returns schema information for the data source of this <see cref="T:Microsoft.Data.SqlClient.SqlConnection" />. For more information about scheme, see [SQL Server Schema Collections](/sql/connect/ado-net/sql-server-schema-collections).</summary>
<returns>A <see cref="T:System.Data.DataTable" /> that contains schema information.</returns>
<remarks>To be added.</remarks>
</GetSchema2>
<GetSchemaCollectionName>
<param name="collectionName">Specifies the name of the schema to return.</param>
<summary>Returns schema information for the data source of this <see cref="T:Microsoft.Data.SqlClient.SqlConnection" /> using the specified string for the schema name.</summary>
<returns>A <see cref="T:System.Data.DataTable" /> that contains schema information.</returns>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
You may need the schema information of the database, tables or columns. This sample:
- Uses GetSchema to get schema information.
- Use schema restrictions to get the specified information.
- Gets schema information of the database, tables, and some columns.
Before you run the sample, you need to create the sample database, using the following Transact-SQL:
```
USE [master]
GO
CREATE DATABASE [MySchool]
GO
USE [MySchool]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Course]([CourseID] [nvarchar](10) NOT NULL,
[Year] [smallint] NOT NULL,
[Title] [nvarchar](100) NOT NULL,
[Credits] [int] NOT NULL,
[DepartmentID] [int] NOT NULL,
CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED
(
[CourseID] ASC,
[Year] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Department]([DepartmentID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[Budget] [money] NOT NULL,
[StartDate] [datetime] NOT NULL,
[Administrator] [int] NULL,
CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED
(
[DepartmentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]
GO
INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C1045', 2012, N'Calculus', 4, 7)
INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C1061', 2012, N'Physics', 4, 1)
INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C2021', 2012, N'Composition', 3, 2)
INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C2042', 2012, N'Literature', 4, 2)
SET IDENTITY_INSERT [dbo].[Department] ON
INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (1, N'Engineering', 350000.0000, CAST(0x0000999C00000000 AS DateTime), 2)
INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (2, N'English', 120000.0000, CAST(0x0000999C00000000 AS DateTime), 6)
INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (4, N'Economics', 200000.0000, CAST(0x0000999C00000000 AS DateTime), 4)
INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (7, N'Mathematics', 250024.0000, CAST(0x0000999C00000000 AS DateTime), 3)
SET IDENTITY_INSERT [dbo].[Department] OFF
ALTER TABLE [dbo].[Course] WITH CHECK ADD CONSTRAINT [FK_Course_Department] FOREIGN KEY([DepartmentID])
REFERENCES [dbo].[Department] ([DepartmentID])
GO
ALTER TABLE [dbo].[Course] CHECK CONSTRAINT [FK_Course_Department]
GO
```
[How to Get Schema Information from Database](https://code.msdn.microsoft.com/How-to-Get-Schema-b66d62e2) has C# and Visual Basic versions of this code sample in a Visual Studio project.
[!code-csharp[SqlConnection.GetSchema#1](~/../sqlclient/doc/samples/SqlConnection_GetSchema.cs#1)]
]]></format>
</remarks>
<exception cref="T:System.ArgumentException">
<paramref name="collectionName" /> is specified as null.</exception>
</GetSchemaCollectionName>
<GetSchemaCollectionNameRestrictionValues>
<param name="collectionName">Specifies the name of the schema to return.</param>
<param name="restrictionValues">A set of restriction values for the requested schema.</param>
<summary>Returns schema information for the data source of this <see cref="T:Microsoft.Data.SqlClient.SqlConnection" /> using the specified string for the schema name and the specified string array for the restriction values.</summary>
<returns>A <see cref="T:System.Data.DataTable" /> that contains schema information.</returns>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
The `restrictionValues` parameter can supply *n* depth of values, which are specified by the restrictions collection for a specific collection. In order to set values on a given restriction, and not set the values of other restrictions, you need to set the preceding restrictions to `null` and then put the appropriate value in for the restriction that you would like to specify a value for.
An example of this is the "Tables" collection. If the "Tables" collection has three restrictions--database, owner, and table name--and you want to get back only the tables associated with the owner "Carl", you need to pass in the following values: null, "Carl". If a restriction value is not passed in, the default values are used for that restriction. This is the same mapping as passing in `null`, which is different from passing in an empty string for the parameter value. In that case, the empty string ("") is considered to be the value for the specified parameter.
For a code sample demonstrating <xref:Microsoft.Data.SqlClient.SqlConnection.GetSchema%2A>, see <xref:Microsoft.Data.SqlClient.SqlConnection.GetSchema%2A>.
]]></format>
</remarks>
<exception cref="T:System.ArgumentException">
<paramref name="collectionName" /> is specified as null.</exception>
<altmember cref="M:Microsoft.Data.SqlClient.SqlConnection.GetSchema" />
</GetSchemaCollectionNameRestrictionValues>
<InfoMessage>
<summary>Occurs when SQL Server returns a warning or informational message.</summary>
<remarks>
<format type="text/markdown"><.
For more information and an example, see [Connection Events](/sql/connect/ado-net/connection-events).
]]></format>
</remarks>
</InfoMessage>
<OnStateChange>
<param name="stateChange">To be added.</param>
<summary>To be added.</summary>
<remarks>To be added.</remarks>
</OnStateChange>
<Open>
<summary>Opens a database connection with the property settings specified by the <see cref="P:Microsoft.Data.SqlClient.SqlConnection.ConnectionString" />.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
The <xref:Microsoft.Data.SqlClient.SqlConnection> draws an open connection from the connection pool if one is available. Otherwise, it establishes a new connection to an instance of SQL Server.
> [!NOTE]
> If the <xref:Microsoft.Data.SqlClient.SqlConnection> goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling <xref:Microsoft.Data.SqlClient.SqlConnection.Close%2A>.
> [!NOTE]
> If you specify a port number other than 1433 when you are trying to connect to an instance of SQL Server and using a protocol other than TCP/IP, the <xref:Microsoft.Data.SqlClient.SqlConnection.Open%2A> method fails. To specify a port number other than 1433, include "server=machinename,port number" in the connection string, and use the TCP/IP protocol.
> [!NOTE]
> The .NET Framework Data Provider for SQL Server requires the Security permission with "Allows calls to unmanaged assemblies" enabled (<xref:System.Security.Permissions.SecurityPermission> with <xref:System.Security.Permissions.SecurityPermissionFlag> set to `UnmanagedCode`) to open a <xref:Microsoft.Data.SqlClient.SqlConnection> with SQL Debugging enabled.
## Examples
The following example creates a <xref:Microsoft.Data.SqlClient.SqlConnection>, opens it, and displays some of its properties. The connection is automatically closed at the end of the `using` block.
[!code-csharp[SqlConnection_Open Example#1](~/../sqlclient/doc/samples/SqlConnection_Open.cs#1)]
]]></format>
</remarks>
<exception cref="T:System.InvalidOperationException">Cannot open a connection without specifying a data source or server.
or
The connection is already open.</exception>
<exception cref="T:Microsoft.Data.SqlClient.SqlException">A connection-level error occurred while opening the connection. If the <see cref="P:Microsoft.Data.SqlClient.SqlException.Number" /> property contains the value 18487 or 18488, this indicates that the specified password has expired or must be reset. See the <see cref="M:Microsoft.Data.SqlClient.SqlConnection.ChangePassword(System.String,System.String)" /> method for more information.
The <see langword="<system.data.localdb>" /> tag in the app.config file has invalid or unknown elements.</exception>
<exception cref="T:System.Configuration.ConfigurationErrorsException">There are two entries with the same name in the <see langword="<localdbinstances>" /> section.</exception>
</Open>
<OpenWithOverrides>
<param name="overrides">Options to override default connection open behavior.</param>
<summary>
Opens a database connection with the property settings specified by the <see cref="P:Microsoft.Data.SqlClient.SqlConnection.ConnectionString" />.
</summary>
<remarks>
<format type="text/markdown">
<![CDATA[
## Remarks
The <xref:Microsoft.Data.SqlClient.SqlConnection> draws an open connection from the connection pool if one is available. Otherwise, it establishes a new connection to an instance of SQL Server. If overrides are specified, the first open attempt will apply the specified overrides to the open action.
> [!NOTE]
> If the <xref:Microsoft.Data.SqlClient.SqlConnection> goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling <xref:Microsoft.Data.SqlClient.SqlConnection.Close%2A>.
> [!NOTE]
> If you specify a port number other than 1433 when you are trying to connect to an instance of SQL Server and using a protocol other than TCP/IP, the <xref:Microsoft.Data.SqlClient.SqlConnection.Open%2A> method fails. To specify a port number other than 1433, include "server=machinename,port number" in the connection string, and use the TCP/IP protocol.
> [!NOTE]
> The .NET Framework Data Provider for SQL Server requires the Security permission with "Allows calls to unmanaged assemblies" enabled (<xref:System.Security.Permissions.SecurityPermission> with <xref:System.Security.Permissions.SecurityPermissionFlag> set to `UnmanagedCode`) to open a <xref:Microsoft.Data.SqlClient.SqlConnection> with SQL Debugging enabled.
## Examples
The following example creates a <xref:Microsoft.Data.SqlClient.SqlConnection>, opens it, and displays some of its properties. The connection is automatically closed at the end of the `using` block.
[!code-csharp[SqlConnection_Open Example#1](~/../sqlclient/doc/samples/SqlConnection_Open.cs#1)]
]]>
</format>
</remarks>
<exception cref="T:System.InvalidOperationException">Cannot open a connection without specifying a data source or server.
or
The connection is already open.
</exception>
<exception cref="T:Microsoft.Data.SqlClient.SqlException">A connection-level error occurred while opening the connection. If the <see cref="P:Microsoft.Data.SqlClient.SqlException.Number" /> property contains the value 18487 or 18488, this indicates that the specified password has expired or must be reset. See the <see cref="M:Microsoft.Data.SqlClient.SqlConnection.ChangePassword(System.String,System.String)" /> method for more information.
The <see langword="<system.data.localdb>" /> tag in the app.config file has invalid or unknown elements.</exception>
<exception cref="T:System.Configuration.ConfigurationErrorsException">There are two entries with the same name in the <see langword="<localdbinstances>" /> section.</exception>
</OpenWithOverrides>
<OpenAsync>
<param name="cancellationToken">The cancellation instruction.</param>
<summary>An asynchronous version of <see cref="M:Microsoft.Data.SqlClient.SqlConnection.Open" />, which opens a database connection with the property settings specified by the <see cref="P:Microsoft.Data.SqlClient.SqlConnection.ConnectionString" />. The cancellation token can be used to request that the operation be abandoned before the connection timeout elapses. Exceptions will be propagated via the returned Task. If the connection timeout time elapses without successfully connecting, the returned Task will be marked as faulted with an Exception. The implementation returns a Task without blocking the calling thread for both pooled and non-pooled connections.</summary>
<returns>A task representing the asynchronous operation.</returns>
<remarks>
<format type="text/markdown"><.
]]></format>
</remarks>
<exception cref="T:System.InvalidOperationException">Calling <see cref="M:Microsoft.Data.SqlClient.SqlConnection.OpenAsync(System.Threading.CancellationToken)" /> more than once for the same instance before task completion.
A connection was not available from the connection pool before the connection time out elapsed.</exception>