DbConnectionStringBuilder DbConnectionStringBuilder DbConnectionStringBuilder DbConnectionStringBuilder Class

定义

提供强类型化连接字符串生成器的基类。Provides a base class for strongly typed connection string builders.

public ref class DbConnectionStringBuilder : System::Collections::IDictionary, System::ComponentModel::ICustomTypeDescriptor
public class DbConnectionStringBuilder : System.Collections.IDictionary, System.ComponentModel.ICustomTypeDescriptor
type DbConnectionStringBuilder = class
    interface IDictionary
    interface ICustomTypeDescriptor
    interface ICollection
    interface IEnumerable
Public Class DbConnectionStringBuilder
Implements ICustomTypeDescriptor, IDictionary
继承
DbConnectionStringBuilderDbConnectionStringBuilderDbConnectionStringBuilderDbConnectionStringBuilder
派生
实现

示例

下面的控制台应用程序构建两个连接字符串,一个用于 Microsoft Jet 数据库,另一个用于 SQL Server 数据库。The following console application builds two connection strings, one for a Microsoft Jet database, and one for a SQL Server database. 在每种情况下,该代码使用DbConnectionStringBuilder泛型类来创建连接字符串,然后将DbConnectionStringBuilder实例的ConnectionString属性传递给强类型连接类的构造函数。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();
}
Sub Main()
    Dim builder As 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)

    ' Note that the DbConnectionStringBuilder class 
    ' is database agnostic, and it's possible to 
    ' build any type of connection string using 
    ' this class.
    ' Notice that the ConnectionString property may have been 
    ' formatted by the DbConnectionStringBuilder class.

    Dim oledbConnect As 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)")

    Dim sqlConnect As 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.Item("Server") = "."
    builder.Remove("User ID")

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

    ' The Item property is the default for the class, 
    ' and setting the Item property adds the value if 
    ' necessary.
    builder("Integrated Security") = True
    builder.Remove("password")
    builder.Item("User ID") = "Hello"
    Console.WriteLine(builder.ConnectionString)

    Console.WriteLine("Press Enter to finish.")
    Console.ReadLine()
End Sub

注解

类提供一个基类,强类型化连接字符串生成器(SqlConnectionStringBuilderOleDbConnectionStringBuilder等)派生自该基类。 DbConnectionStringBuilderThe 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.

DbConnectionStringBuilder已采用与数据库无关的方式定义。The DbConnectionStringBuilder has been defined in a database-agnostic manner. 由于添加了System.Data.Common命名空间,因此开发人员需要一个基类,使其可以对任意数据库进行编程以生成连接字符串。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. 因此, DbConnectionStringBuilder类允许用户分配任意键/值对,并将生成的连接字符串传递给强类型提供程序。Therefore, the DbConnectionStringBuilder class lets users assign arbitrary key/value pairs and pass the resulting connection string to a strongly typed provider. 作为 .NET Framework 的一部分包含的所有数据提供程序都提供了一个DbConnectionStringBuilder从继承的强类型化类: OracleConnectionStringBuilder SqlConnectionStringBuilderOdbcConnectionStringBuilder、和OleDbConnectionStringBuilderAll 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.

DbConnectionStringBuilder 类实现 ICustomTypeDescriptor 接口。The DbConnectionStringBuilder class implements the ICustomTypeDescriptor interface. 这意味着该类在设计时适用于 Visual Studio 设计器。This means that the class works with Visual Studio designers at design time. 当开发人员使用设计器在 Visual Studio 中生成强类型化数据集和强类型连接时,强类型连接字符串生成器类将显示与其类型关联的属性,并且还将具有可映射已知密钥的公共值。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.

需要在应用程序中创建连接字符串的开发人员可以使用DbConnectionStringBuilder类或它的某个强类型化派生来生成和修改连接字符串。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. DbConnectionStringBuilder类还可以轻松管理存储在应用程序配置文件中的连接字符串。The DbConnectionStringBuilder class also makes it easy to manage connection strings stored in an application configuration file.

开发人员可以使用强类型连接字符串生成器类创建连接字符串,也可以使用DbConnectionStringBuilder类。Developers can create connection strings using either a strongly typed connection string builder class, or they can use the DbConnectionStringBuilder class. 不会对有效的键/值对执行检查。DbConnectionStringBuilderThe DbConnectionStringBuilder performs no checks for valid key/value pairs. 因此,使用此类可能会创建出无效的连接字符串。Therefore, it is possible using this class to create invalid connection strings. SqlConnectionStringBuilder支持 SQL Server 支持的键/值对; 尝试添加无效对会引发异常。The SqlConnectionStringBuilder supports only key/value pairs that are supported by SQL Server; trying to add invalid pairs will throw an exception.

Add方法和Item[String]属性句柄都尝试插入恶意条目。Both the Add method and Item[String] property handle tries to insert malicious entries. 例如,下面的代码正确转义了嵌套的键/值对:For example, the following code correctly escapes the nested key/value pair:

Dim builder As New System.Data.Common.DbConnectionStringBuilder  
builder("Data Source") = "(local)"  
builder("integrated sSecurity") = True  
builder("Initial Catalog") = "AdventureWorks;NewValue=Bad"  
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"  

构造函数

DbConnectionStringBuilder() DbConnectionStringBuilder() DbConnectionStringBuilder() DbConnectionStringBuilder()

初始化 DbConnectionStringBuilder 类的新实例。Initializes a new instance of the DbConnectionStringBuilder class.

DbConnectionStringBuilder(Boolean) DbConnectionStringBuilder(Boolean) DbConnectionStringBuilder(Boolean) DbConnectionStringBuilder(Boolean)

初始化 DbConnectionStringBuilder 类的新实例,可以选择使用 ODBC 规则来引用值。Initializes a new instance of the DbConnectionStringBuilder class, optionally using ODBC rules for quoting values.

属性

BrowsableConnectionString BrowsableConnectionString BrowsableConnectionString BrowsableConnectionString

获取或设置一个值,该值指示 ConnectionString 属性是否在 Visual Studio 设计器中可见。Gets or sets a value that indicates whether the ConnectionString property is visible in Visual Studio designers.

ConnectionString ConnectionString ConnectionString ConnectionString

获取或设置与 DbConnectionStringBuilder 相关联的连接字符串。Gets or sets the connection string associated with the DbConnectionStringBuilder.

Count Count Count Count

获取属性 ConnectionString 中包含的键的当前数目。Gets the current number of keys that are contained within the ConnectionString property.

IsFixedSize IsFixedSize IsFixedSize IsFixedSize

获取一个值,该值指示 DbConnectionStringBuilder 是否具有固定大小。Gets a value that indicates whether the DbConnectionStringBuilder has a fixed size.

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

获取一个值,该值指示 DbConnectionStringBuilder 是否为只读。Gets a value that indicates whether the DbConnectionStringBuilder is read-only.

Item[String] Item[String] Item[String] Item[String]

获取或设置与指定的键关联的值。Gets or sets the value associated with the specified key.

Keys Keys Keys Keys

获取包含 ICollection 中的键的 DbConnectionStringBuilderGets an ICollection that contains the keys in the DbConnectionStringBuilder.

Values Values Values Values

获取包含 ICollection 中的值的 DbConnectionStringBuilderGets an ICollection that contains the values in the DbConnectionStringBuilder.

方法

Add(String, Object) Add(String, Object) Add(String, Object) Add(String, Object)

将带有指定键和值的条目添加到 DbConnectionStringBuilder 中。Adds an entry with the specified key and value into the DbConnectionStringBuilder.

AppendKeyValuePair(StringBuilder, String, String) AppendKeyValuePair(StringBuilder, String, String) AppendKeyValuePair(StringBuilder, String, String) AppendKeyValuePair(StringBuilder, String, String)

提供了一种有效而安全的方法,用于将键和值附加到现有的 StringBuilder 对象中。Provides an efficient and safe way to append a key and value to an existing StringBuilder object.

AppendKeyValuePair(StringBuilder, String, String, Boolean) AppendKeyValuePair(StringBuilder, String, String, Boolean) AppendKeyValuePair(StringBuilder, String, String, Boolean) AppendKeyValuePair(StringBuilder, String, String, Boolean)

提供了一种有效而安全的方法,用于将键和值附加到现有的 StringBuilder 对象中。Provides an efficient and safe way to append a key and value to an existing StringBuilder object.

Clear() Clear() Clear() Clear()

清除 DbConnectionStringBuilder 实例的内容。Clears the contents of the DbConnectionStringBuilder instance.

ClearPropertyDescriptors() ClearPropertyDescriptors() ClearPropertyDescriptors() ClearPropertyDescriptors()

清除关联的 DbConnectionStringBuilder 上的 PropertyDescriptor 对象集合。Clears the collection of PropertyDescriptor objects on the associated DbConnectionStringBuilder.

ContainsKey(String) ContainsKey(String) ContainsKey(String) ContainsKey(String)

确定 DbConnectionStringBuilder 是否包含特定键。Determines whether the DbConnectionStringBuilder contains a specific key.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
EquivalentTo(DbConnectionStringBuilder) EquivalentTo(DbConnectionStringBuilder) EquivalentTo(DbConnectionStringBuilder) EquivalentTo(DbConnectionStringBuilder)

将此 DbConnectionStringBuilder 对象中的连接信息与提供的对象中的连接信息进行比较。Compares the connection information in this DbConnectionStringBuilder object with the connection information in the supplied object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetProperties(Hashtable) GetProperties(Hashtable) GetProperties(Hashtable) GetProperties(Hashtable)

使用有关此 DbConnectionStringBuilder 的所有属性的信息,填充提供的 HashtableFills a supplied Hashtable with information about all the properties of this DbConnectionStringBuilder.

GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
Remove(String) Remove(String) Remove(String) Remove(String)

DbConnectionStringBuilder 实例中移除具有指定的键的项。Removes the entry with the specified key from the DbConnectionStringBuilder instance.

ShouldSerialize(String) ShouldSerialize(String) ShouldSerialize(String) ShouldSerialize(String)

指示此 DbConnectionStringBuilder 实例中是否存在指定的键。Indicates whether the specified key exists in this DbConnectionStringBuilder instance.

ToString() ToString() ToString() ToString()

返回与此 DbConnectionStringBuilder 关联的连接字符串。Returns the connection string associated with this DbConnectionStringBuilder.

TryGetValue(String, Object) TryGetValue(String, Object) TryGetValue(String, Object) TryGetValue(String, Object)

从此 DbConnectionStringBuilder 中检索与提供的键相对应的值。Retrieves a value corresponding to the supplied key from this DbConnectionStringBuilder.

显式界面实现

ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32)

从特定的 ICollection 索引开始,将 Array 的元素复制到一个 Array 中。Copies the elements of the ICollection to an Array, starting at a particular Array index.

ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized

获取一个值,该值指示是否同步对 ICollection 的访问(线程安全)。Gets a value indicating whether access to the ICollection is synchronized (thread safe).

ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot

获取可用于同步对 ICollection 的访问的对象。Gets an object that can be used to synchronize access to the ICollection.

ICustomTypeDescriptor.GetAttributes() ICustomTypeDescriptor.GetAttributes() ICustomTypeDescriptor.GetAttributes() ICustomTypeDescriptor.GetAttributes()

返回此组件实例的自定义属性的集合。Returns a collection of custom attributes for this instance of a component.

ICustomTypeDescriptor.GetClassName() ICustomTypeDescriptor.GetClassName() ICustomTypeDescriptor.GetClassName() ICustomTypeDescriptor.GetClassName()

返回此组件实例的类名称。Returns the class name of this instance of a component.

ICustomTypeDescriptor.GetComponentName() ICustomTypeDescriptor.GetComponentName() ICustomTypeDescriptor.GetComponentName() ICustomTypeDescriptor.GetComponentName()

返回某个组件的此实例的名称。Returns the name of this instance of a component.

ICustomTypeDescriptor.GetConverter() ICustomTypeDescriptor.GetConverter() ICustomTypeDescriptor.GetConverter() ICustomTypeDescriptor.GetConverter()

返回此组件实例的类型转换器。Returns a type converter for this instance of a component.

ICustomTypeDescriptor.GetDefaultEvent() ICustomTypeDescriptor.GetDefaultEvent() ICustomTypeDescriptor.GetDefaultEvent() ICustomTypeDescriptor.GetDefaultEvent()

返回某个组件的此实例的默认事件。Returns the default event for this instance of a component.

ICustomTypeDescriptor.GetDefaultProperty() ICustomTypeDescriptor.GetDefaultProperty() ICustomTypeDescriptor.GetDefaultProperty() ICustomTypeDescriptor.GetDefaultProperty()

返回此组件实例的默认属性。Returns the default property for this instance of a component.

ICustomTypeDescriptor.GetEditor(Type) ICustomTypeDescriptor.GetEditor(Type) ICustomTypeDescriptor.GetEditor(Type) ICustomTypeDescriptor.GetEditor(Type)

返回此组件实例的指定类型的编辑器。Returns an editor of the specified type for this instance of a component.

ICustomTypeDescriptor.GetEvents() ICustomTypeDescriptor.GetEvents() ICustomTypeDescriptor.GetEvents() ICustomTypeDescriptor.GetEvents()

返回此组件实例的事件。Returns the events for this instance of a component.

ICustomTypeDescriptor.GetEvents(Attribute[]) ICustomTypeDescriptor.GetEvents(Attribute[]) ICustomTypeDescriptor.GetEvents(Attribute[]) ICustomTypeDescriptor.GetEvents(Attribute[])

使用指定的属性数组作为筛选器,返回此组件实例的事件。Returns the events for this instance of a component using the specified attribute array as a filter.

ICustomTypeDescriptor.GetProperties() ICustomTypeDescriptor.GetProperties() ICustomTypeDescriptor.GetProperties() ICustomTypeDescriptor.GetProperties()

返回此组件实例的属性。Returns the properties for this instance of a component.

ICustomTypeDescriptor.GetProperties(Attribute[]) ICustomTypeDescriptor.GetProperties(Attribute[]) ICustomTypeDescriptor.GetProperties(Attribute[]) ICustomTypeDescriptor.GetProperties(Attribute[])

使用特性数组作为筛选器,返回此组件实例的属性。Returns the properties for this instance of a component using the attribute array as a filter.

ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor) ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor) ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor) ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor)

返回一个对象,该对象包含指定的属性描述符所描述的属性。Returns an object that contains the property described by the specified property descriptor.

IDictionary.Add(Object, Object) IDictionary.Add(Object, Object) IDictionary.Add(Object, Object) IDictionary.Add(Object, Object)

IDictionary 对象中添加一个带有所提供的键和值的元素。Adds an element with the provided key and value to the IDictionary object.

IDictionary.Contains(Object) IDictionary.Contains(Object) IDictionary.Contains(Object) IDictionary.Contains(Object)

确定 IDictionary 对象是否包含具有指定键的元素。Determines whether the IDictionary object contains an element with the specified key.

IDictionary.GetEnumerator() IDictionary.GetEnumerator() IDictionary.GetEnumerator() IDictionary.GetEnumerator()

返回 IDictionary 对象的 IDictionaryEnumerator 对象。Returns an IDictionaryEnumerator object for the IDictionary object.

IDictionary.IsFixedSize IDictionary.IsFixedSize IDictionary.IsFixedSize IDictionary.IsFixedSize
IDictionary.IsReadOnly IDictionary.IsReadOnly IDictionary.IsReadOnly IDictionary.IsReadOnly
IDictionary.Item[Object] IDictionary.Item[Object] IDictionary.Item[Object] IDictionary.Item[Object]

获取或设置具有指定键的元素。Gets or sets the element with the specified key.

IDictionary.Remove(Object) IDictionary.Remove(Object) IDictionary.Remove(Object) IDictionary.Remove(Object)

IDictionary 对象中移除具有指定键的元素。Removes the element with the specified key from the IDictionary object.

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

返回循环访问集合的枚举数。Returns an enumerator that iterates through a collection.

扩展方法

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

适用于

另请参阅