3 out of 4 rated this helpful - Rate this topic

SqlConnectionStringBuilder Class

Provides a simple way to create and manage the contents of connection strings used by the SqlConnection class.

System.Object
  System.Data.Common.DbConnectionStringBuilder
    System.Data.SqlClient.SqlConnectionStringBuilder

Namespace:  System.Data.SqlClient
Assembly:  System.Data (in System.Data.dll)
public sealed class SqlConnectionStringBuilder : DbConnectionStringBuilder

The SqlConnectionStringBuilder type exposes the following members.

  Name Description
Public method SqlConnectionStringBuilder() Initializes a new instance of the SqlConnectionStringBuilder class.
Public method SqlConnectionStringBuilder(String) Initializes a new instance of the SqlConnectionStringBuilder class. The provided connection string provides the data for the instance's internal connection information.
Top
  Name Description
Public property ApplicationIntent Declares the application workload type when connecting to a database in an SQL Server Availability Group. You can set the value of this property with ApplicationIntent. For more information about SqlClient support for Always On Availability Groups, see SqlClient Support for High Availability, Disaster Recovery.
Public property ApplicationName Gets or sets the name of the application associated with the connection string.
Public property AsynchronousProcessing Gets or sets a Boolean value that indicates whether asynchronous processing is allowed by the connection created by using this connection string.
Public property AttachDBFilename Gets or sets a string that contains the name of the primary data file. This includes the full path name of an attachable database.
Public property BrowsableConnectionString Gets or sets a value that indicates whether the ConnectionString property is visible in Visual Studio designers. (Inherited from DbConnectionStringBuilder.)
Public property ConnectionReset Obsolete. Obsolete. Gets or sets a Boolean value that indicates whether the connection is reset when drawn from the connection pool.
Public property ConnectionString Gets or sets the connection string associated with the DbConnectionStringBuilder. (Inherited from DbConnectionStringBuilder.)
Public property ConnectTimeout Gets or sets the length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.
Public property ContextConnection Gets or sets a value that indicates whether a client/server or in-process connection to SQL Server should be made.
Public property Count Gets the current number of keys that are contained within the ConnectionString property. (Inherited from DbConnectionStringBuilder.)
Public property CurrentLanguage Gets or sets the SQL Server Language record name.
Public property DataSource Gets or sets the name or network address of the instance of SQL Server to connect to.
Public property Encrypt Gets or sets a Boolean value that indicates whether SQL Server uses SSL encryption for all data sent between the client and server if the server has a certificate installed.
Public property Enlist Gets or sets a Boolean value that indicates whether the SQL Server connection pooler automatically enlists the connection in the creation thread's current transaction context.
Public property FailoverPartner Gets or sets the name or address of the partner server to connect to if the primary server is down.
Public property InitialCatalog Gets or sets the name of the database associated with the connection.
Public property IntegratedSecurity Gets or sets a Boolean value that indicates whether User ID and Password are specified in the connection (when false) or whether the current Windows account credentials are used for authentication (when true).
Public property IsFixedSize Gets a value that indicates whether the SqlConnectionStringBuilder has a fixed size. (Overrides DbConnectionStringBuilder.IsFixedSize.)
Public property IsReadOnly Gets a value that indicates whether the DbConnectionStringBuilder is read-only. (Inherited from DbConnectionStringBuilder.)
Public property Item Gets or sets the value associated with the specified key. In C#, this property is the indexer. (Overrides DbConnectionStringBuilder.Item[String].)
Public property Keys Gets an ICollection that contains the keys in the SqlConnectionStringBuilder. (Overrides DbConnectionStringBuilder.Keys.)
Public property LoadBalanceTimeout Gets or sets the minimum time, in seconds, for the connection to live in the connection pool before being destroyed.
Public property MaxPoolSize Gets or sets the maximum number of connections allowed in the connection pool for this specific connection string.
Public property MinPoolSize Gets or sets the minimum number of connections allowed in the connection pool for this specific connection string.
Public property MultipleActiveResultSets Gets or sets a Boolean value that indicates whether multiple active result sets can be associated with the associated connection.
Public property MultiSubnetFailover If your application is connecting to an AlwaysOn availability group (AG) on different subnets, setting MultiSubnetFailover=true provides faster detection of and connection to the (currently) active server. For more information about SqlClient support for Always On Availability Groups, see SqlClient Support for High Availability, Disaster Recovery.
Public property NetworkLibrary Gets or sets a string that contains the name of the network library used to establish a connection to the SQL Server.
Public property PacketSize Gets or sets the size in bytes of the network packets used to communicate with an instance of SQL Server.
Public property Password Gets or sets the password for the SQL Server account.
Public property PersistSecurityInfo Gets or sets a Boolean value that indicates if security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state.
Public property Pooling Gets or sets a Boolean value that indicates whether the connection will be pooled or explicitly opened every time that the connection is requested.
Public property Replication Gets or sets a Boolean value that indicates whether replication is supported using the connection.
Public property TransactionBinding Gets or sets a string value that indicates how the connection maintains its association with an enlisted System.Transactions transaction.
Public property TrustServerCertificate Gets or sets a value that indicates whether the channel will be encrypted while bypassing walking the certificate chain to validate trust.
Public property TypeSystemVersion Gets or sets a string value that indicates the type system the application expects.
Public property UserID Gets or sets the user ID to be used when connecting to SQL Server.
Public property UserInstance Gets or sets 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.
Public property Values Gets an ICollection that contains the values in the SqlConnectionStringBuilder. (Overrides DbConnectionStringBuilder.Values.)
Public property WorkstationID Gets or sets the name of the workstation connecting to SQL Server.
Top
  Name Description
Public method Add Adds an entry with the specified key and value into the DbConnectionStringBuilder. (Inherited from DbConnectionStringBuilder.)
Public method Clear Clears the contents of the SqlConnectionStringBuilder instance. (Overrides DbConnectionStringBuilder.Clear().)
Protected method ClearPropertyDescriptors Clears the collection of PropertyDescriptor objects on the associated DbConnectionStringBuilder. (Inherited from DbConnectionStringBuilder.)
Public method ContainsKey Determines whether the SqlConnectionStringBuilder contains a specific key. (Overrides DbConnectionStringBuilder.ContainsKey(String).)
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Public method EquivalentTo Compares the connection information in this DbConnectionStringBuilder object with the connection information in the supplied object. (Inherited from DbConnectionStringBuilder.)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Protected method GetProperties Fills a supplied Hashtable with information about all the properties of this DbConnectionStringBuilder. (Inherited from DbConnectionStringBuilder.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Remove Removes the entry with the specified key from the SqlConnectionStringBuilder instance. (Overrides DbConnectionStringBuilder.Remove(String).)
Public method ShouldSerialize Indicates whether the specified key exists in this SqlConnectionStringBuilder instance. (Overrides DbConnectionStringBuilder.ShouldSerialize(String).)
Public method ToString Returns the connection string associated with this DbConnectionStringBuilder. (Inherited from DbConnectionStringBuilder.)
Public method TryGetValue Retrieves a value corresponding to the supplied key from this SqlConnectionStringBuilder. (Overrides DbConnectionStringBuilder.TryGetValue(String, Object).)
Top
  Name Description
Explicit interface implemetation Private method ICollection.CopyTo Copies the elements of the ICollection to an Array, starting at a particular Array index. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private property ICollection.IsSynchronized Gets a value indicating whether access to the ICollection is synchronized (thread safe). (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private property ICollection.SyncRoot Gets an object that can be used to synchronize access to the ICollection. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method ICustomTypeDescriptor.GetAttributes Returns a collection of custom attributes for this instance of a component. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method ICustomTypeDescriptor.GetClassName Returns the class name of this instance of a component. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method ICustomTypeDescriptor.GetComponentName Returns the name of this instance of a component. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method ICustomTypeDescriptor.GetConverter Returns a type converter for this instance of a component. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method ICustomTypeDescriptor.GetDefaultEvent Returns the default event for this instance of a component. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method ICustomTypeDescriptor.GetDefaultProperty Returns the default property for this instance of a component. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method ICustomTypeDescriptor.GetEditor Returns an editor of the specified type for this instance of a component. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method ICustomTypeDescriptor.GetEvents() Returns the events for this instance of a component. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method ICustomTypeDescriptor.GetEvents(Attribute[]) Returns the events for this instance of a component using the specified attribute array as a filter. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method ICustomTypeDescriptor.GetProperties() Returns the properties for this instance of a component. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method ICustomTypeDescriptor.GetProperties(Attribute[]) Returns the properties for this instance of a component using the attribute array as a filter. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method ICustomTypeDescriptor.GetPropertyOwner Returns an object that contains the property described by the specified property descriptor. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method IDictionary.Add Adds an element with the provided key and value to the IDictionary object. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method IDictionary.Contains Determines whether the IDictionary object contains an element with the specified key. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method IDictionary.GetEnumerator Returns an IDictionaryEnumerator object for the IDictionary object. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private property IDictionary.Item Gets or sets the element with the specified key. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method IDictionary.Remove Removes the element with the specified key from the IDictionary object. (Inherited from DbConnectionStringBuilder.)
Explicit interface implemetation Private method IEnumerable.GetEnumerator Returns an enumerator that iterates through a collection. (Inherited from DbConnectionStringBuilder.)
Top

The connection string builder lets developers programmatically create syntactically correct connection strings, and parse and rebuild existing connection strings, using properties and methods of the class. The connection string builder provides strongly typed properties corresponding to the known key/value pairs allowed by SQL Server. Developers needing to create connection strings as part of applications can use the SqlConnectionStringBuilder class to build and modify connection strings. The class also makes it easy to manage connection strings stored in an application configuration file.

The SqlConnectionStringBuilder performs checks for valid key/value pairs. Therefore, you cannot use this class to create invalid connection strings; trying to add invalid pairs will throw an exception. The class maintains a fixed collection of synonyms and can translate from a synonym to the corresponding well-known key name.

For example, when you use the Item property to retrieve a value, you can specify a string that contains any synonym for the key you need. For example, you can specify "Network Address", "addr", or any other acceptable synonym for this key within a connection string when you use any member that requires a string that contains the key name, such as the Item property or the Remove method. See the ConnectionString property for a full list of acceptable synonyms.

The Item property handles tries to insert malicious entries. For example, the following code, using the default Item property (the indexer, in C#) correctly escapes the nested key/value pair:

[Visual Basic]

Dim builder As New System.Data.SqlClient.SqlConnectionStringBuilder
builder("Data Source") = "(local)"
builder("Integrated Security") = True
builder("Initial Catalog") = "AdventureWorks;NewValue=Bad"
Console.WriteLine(builder.ConnectionString)

[C#]

System.Data.SqlClient.SqlConnectionStringBuilder builder =
  new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["integrated Security"] = true;
builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);

The result is the following connection string that handles the invalid value in a safe manner:

Source=(local);Initial Catalog="AdventureWorks;NewValue=Bad";
Integrated Security=True

The following console application builds connection strings for a SQL Server 2005 database. The code uses a SqlConnectionStringBuilder class to create the connection string, and then passes the ConnectionString property of the SqlConnectionStringBuilder instance to the constructor of the connection class. The example also parses an existing connection string and demonstrates various ways of manipulating the connection string's contents.

Note Note

This example includes a password to demonstrate how SqlConnectionStringBuilder works with connection strings. In your applications, we recommend that you use Windows Authentication. If you must use a password, do not include a hard-coded password in your application.


using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        // Create a new SqlConnectionStringBuilder and
        // initialize it with a few name/value pairs.
        SqlConnectionStringBuilder builder =
            new SqlConnectionStringBuilder(GetConnectionString());

        // The input connection string used the 
        // Server key, but the new connection string uses
        // the well-known Data Source key instead.
        Console.WriteLine(builder.ConnectionString);

        // Pass the SqlConnectionStringBuilder an existing 
        // connection string, and you can retrieve and
        // modify any of the elements.
        builder.ConnectionString = "server=(local);user id=ab;" +
            "password= a!Pass113;initial catalog=AdventureWorks";

        // Now that the connection string has been parsed,
        // you can work with individual items.
        Console.WriteLine(builder.Password);
        builder.Password = "new@1Password";
        builder.AsynchronousProcessing = true;

        // You can refer to connection keys using strings, 
        // as well. When you use this technique (the default
        // Item property in Visual Basic, or the indexer in C#),
        // you can specify any synonym for the connection string key
        // name.
        builder["Server"] = ".";
        builder["Connect Timeout"] = 1000;
        builder["Trusted_Connection"] = true;
        Console.WriteLine(builder.ConnectionString);

        Console.WriteLine("Press Enter to finish.");
        Console.ReadLine();
    }

    private static string GetConnectionString()
    {
        // To avoid storing the connection string in your code,
        // you can retrieve it from a configuration file. 
        return "Server=(local);Integrated Security=SSPI;" +
            "Initial Catalog=AdventureWorks";
    }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ