Export (0) Print
Expand All

DbConnectionStringBuilder Class

Provides a base class for strongly typed connection string builders.

Namespace:  System.Data.Common
Assembly:  System.Data (in System.Data.dll)

public class DbConnectionStringBuilder : IDictionary, 
	ICollection, IEnumerable, ICustomTypeDescriptor

The DbConnectionStringBuilder type exposes the following members.

  NameDescription
Public methodDbConnectionStringBuilder()Initializes a new instance of the DbConnectionStringBuilder class.
Public methodDbConnectionStringBuilder(Boolean)Initializes a new instance of the DbConnectionStringBuilder class, optionally using ODBC rules for quoting values.
Top

  NameDescription
Public propertyBrowsableConnectionStringGets or sets a value that indicates whether the ConnectionString property is visible in Visual Studio designers.
Public propertyConnectionStringGets or sets the connection string associated with the DbConnectionStringBuilder.
Public propertyCountGets the current number of keys that are contained within the ConnectionString property.
Public propertyIsFixedSizeGets a value that indicates whether the DbConnectionStringBuilder has a fixed size.
Public propertyIsReadOnlyGets a value that indicates whether the DbConnectionStringBuilder is read-only.
Public propertyItemGets or sets the value associated with the specified key.
Public propertyKeysGets an ICollection that contains the keys in the DbConnectionStringBuilder.
Public propertyValuesGets an ICollection that contains the values in the DbConnectionStringBuilder.
Top

  NameDescription
Public methodAddAdds an entry with the specified key and value into the DbConnectionStringBuilder.
Public methodStatic memberAppendKeyValuePair(StringBuilder, String, String)Provides an efficient and safe way to append a key and value to an existing StringBuilder object.
Public methodStatic memberAppendKeyValuePair(StringBuilder, String, String, Boolean)Provides an efficient and safe way to append a key and value to an existing StringBuilder object.
Public methodClearClears the contents of the DbConnectionStringBuilder instance.
Protected methodClearPropertyDescriptorsClears the collection of PropertyDescriptor objects on the associated DbConnectionStringBuilder.
Public methodContainsKeyDetermines whether the DbConnectionStringBuilder contains a specific key.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodEquivalentToCompares the connection information in this DbConnectionStringBuilder object with the connection information in the supplied object.
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Protected methodGetPropertiesFills a supplied Hashtable with information about all the properties of this DbConnectionStringBuilder.
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodRemoveRemoves the entry with the specified key from the DbConnectionStringBuilder instance.
Public methodShouldSerializeIndicates whether the specified key exists in this DbConnectionStringBuilder instance.
Public methodToStringReturns the connection string associated with this DbConnectionStringBuilder. (Overrides Object.ToString().)
Public methodTryGetValueRetrieves a value corresponding to the supplied key from this DbConnectionStringBuilder.
Top

  NameDescription
Public Extension MethodAsParallelEnables parallelization of a query. (Defined by ParallelEnumerable.)
Public Extension MethodAsQueryableConverts an IEnumerable to an IQueryable. (Defined by Queryable.)
Public Extension MethodCast<TResult>Casts the elements of an IEnumerable to the specified type. (Defined by Enumerable.)
Public Extension MethodOfType<TResult>Filters the elements of an IEnumerable based on a specified type. (Defined by Enumerable.)
Top

  NameDescription
Explicit interface implemetationPrivate methodICollection.CopyToCopies the elements of the ICollection to an Array, starting at a particular Array index.
Explicit interface implemetationPrivate propertyICollection.IsSynchronizedGets a value indicating whether access to the ICollection is synchronized (thread safe).
Explicit interface implemetationPrivate propertyICollection.SyncRootGets an object that can be used to synchronize access to the ICollection.
Explicit interface implemetationPrivate methodICustomTypeDescriptor.GetAttributesReturns a collection of custom attributes for this instance of a component.
Explicit interface implemetationPrivate methodICustomTypeDescriptor.GetClassNameReturns the class name of this instance of a component.
Explicit interface implemetationPrivate methodICustomTypeDescriptor.GetComponentNameReturns the name of this instance of a component.
Explicit interface implemetationPrivate methodICustomTypeDescriptor.GetConverterReturns a type converter for this instance of a component.
Explicit interface implemetationPrivate methodICustomTypeDescriptor.GetDefaultEventReturns the default event for this instance of a component.
Explicit interface implemetationPrivate methodICustomTypeDescriptor.GetDefaultPropertyReturns the default property for this instance of a component.
Explicit interface implemetationPrivate methodICustomTypeDescriptor.GetEditorReturns an editor of the specified type for this instance of a component.
Explicit interface implemetationPrivate methodICustomTypeDescriptor.GetEvents()Returns the events for this instance of a component.
Explicit interface implemetationPrivate methodICustomTypeDescriptor.GetEvents(Attribute[])Returns the events for this instance of a component using the specified attribute array as a filter.
Explicit interface implemetationPrivate methodICustomTypeDescriptor.GetProperties()Returns the properties for this instance of a component.
Explicit interface implemetationPrivate methodICustomTypeDescriptor.GetProperties(Attribute[])Returns the properties for this instance of a component using the attribute array as a filter.
Explicit interface implemetationPrivate methodICustomTypeDescriptor.GetPropertyOwnerReturns an object that contains the property described by the specified property descriptor.
Explicit interface implemetationPrivate methodIDictionary.AddAdds an element with the provided key and value to the IDictionary object.
Explicit interface implemetationPrivate methodIDictionary.ContainsDetermines whether the IDictionary object contains an element with the specified key.
Explicit interface implemetationPrivate methodIDictionary.GetEnumeratorReturns an IDictionaryEnumerator object for the IDictionary object.
Explicit interface implemetationPrivate propertyIDictionary.ItemGets or sets the element with the specified key.
Explicit interface implemetationPrivate methodIDictionary.RemoveRemoves the element with the specified key from the IDictionary object.
Explicit interface implemetationPrivate methodIEnumerable.GetEnumeratorReturns an enumerator that iterates through a collection.
Top

The DbConnectionStringBuilder class provides the base class from which the strongly typed connection string builders (SqlConnectionStringBuilder, OleDbConnectionStringBuilder, and so on) derive. The connection string builders let developers programmatically create syntactically correct connection strings, and parse and rebuild existing connection strings.

The DbConnectionStringBuilder has been defined in a database-agnostic manner. Because of the addition of the System.Data.Common namespace, developers require a base class against which they can program in order to build connection strings that can work against an arbitrary database. Therefore, the DbConnectionStringBuilder class lets users assign arbitrary key/value pairs and pass the resulting connection string to a strongly typed provider. All the data providers that are included as part of the .NET Framework provide a strongly typed class that inherits from DbConnectionStringBuilder: SqlConnectionStringBuilder, OracleConnectionStringBuilder, OdbcConnectionStringBuilder, and OleDbConnectionStringBuilder.

The developer can build, assign, and edit connection strings for any arbitrary provider. For providers that support specific key/value pairs, the connection string builder provides strongly typed properties corresponding to the known pairs. In order to support providers that require the ability to support unknown values, developers can also supply arbitrary key/value pairs.

The DbConnectionStringBuilder class implements the ICustomTypeDescriptor interface. This means that the class works with Visual Studio designers at design time. When developers use the designer to build strongly typed DataSets and strongly typed connections within Visual Studio, the strongly typed connection string builder class will display the properties associated with its type and will also have converters that can map common values for known keys.

Developers needing to create connection strings as part of applications can use the DbConnectionStringBuilder class or one of its strongly typed derivatives to build and modify connection strings. The DbConnectionStringBuilder class also makes it easy to manage connection strings stored in an application configuration file.

Developers can create connection strings using either a strongly typed connection string builder class, or they can use the DbConnectionStringBuilder class. The DbConnectionStringBuilder performs no checks for valid key/value pairs. Therefore, it is possible using this class to create invalid connection strings. The SqlConnectionStringBuilder supports only key/value pairs that are supported by SQL Server; trying to add invalid pairs will throw an exception.

Both the Add method and Item property handle tries to insert malicious entries. For example, the following code correctly escapes the nested key/value pair:

[Visual Basic]

Dim builder As New System.Data.Common.DbConnectionStringBuilder
builder("Data Source") = "(local)"
builder("integrated sSecurity") = True
builder("Initial Catalog") = "AdventureWorks;NewValue=Bad"

[C#]

System.Data.Common.DbConnectionStringBuilder builder = 
    new System.Data.Common.DbConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["integrated Security"] = true;
builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";

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

data source=(local);integrated security=True;
initial catalog="AdventureWorks;NewValue=Bad"

The following console application builds two connection strings, one for a Microsoft Jet database, and one for a SQL Server database. In each case, the code uses a generic DbConnectionStringBuilder class to create the connection string, and then passes the ConnectionString property of the DbConnectionStringBuilder instance to the constructor of the strongly type connection class. This is not required; the code could also have created individual strongly typed connection string builder instances. The example also parses an existing connection string, and demonstrates various ways of manipulating the connection string's contents.

static void Main()
{
    DbConnectionStringBuilder builder =
        new DbConnectionStringBuilder();
    builder.ConnectionString = @"Data Source=c:\MyData\MyDb.mdb";
    builder.Add("Provider", "Microsoft.Jet.Oledb.4.0");
    builder.Add("Jet OLEDB:Database Password", "*******");
    builder.Add("Jet OLEDB:System Database",
        @"c:\MyData\Workgroup.mdb");
    // Set up row-level locking.
    builder.Add("Jet OLEDB:Database Locking Mode", 1);

    // The DbConnectionStringBuilder class  
    // is database agnostic, so it's possible to  
    // build any type of connection string using  
    // this class. 

    // The ConnectionString property may have been  
    // formatted by the DbConnectionStringBuilder class.
    OleDbConnection oledbConnect = new
        OleDbConnection(builder.ConnectionString);
    Console.WriteLine(oledbConnect.ConnectionString);

    // Use the same DbConnectionStringBuilder to create  
    // a SqlConnection object.
    builder.Clear();
    builder.Add("integrated security", true);
    builder.Add("Initial Catalog", "AdventureWorks");
    builder.Add("Data Source", "(local)");

    SqlConnection sqlConnect = new
        SqlConnection(builder.ConnectionString);
    Console.WriteLine(sqlConnect.ConnectionString);

    // Pass the DbConnectionStringBuilder an existing  
    // connection string, and you can retrieve and 
    // modify any of the elements.
    builder.ConnectionString = "server=(local);user id=*******;" +
        "password=*******;initial catalog=AdventureWorks";
    builder["Server"] = ".";
    builder.Remove("User ID");

    // Note that calling Remove on a nonexistent item doesn't 
    // throw an exception.
    builder.Remove("BadItem");

    // Setting the indexer adds the value if  
    // necessary.
    builder["Integrated Security"] = true;
    builder.Remove("password");
    builder["User ID"] = "Hello";
    Console.WriteLine(builder.ConnectionString);

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

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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.
Show:
© 2014 Microsoft