OdbcConnection 类

定义

表示到数据源的连接是打开的。Represents an open connection to a data source.

public ref class OdbcConnection sealed : System::Data::Common::DbConnection, ICloneable
public ref class OdbcConnection sealed : System::ComponentModel::Component, ICloneable, IDisposable, System::Data::IDbConnection
public sealed class OdbcConnection : System.Data.Common.DbConnection, ICloneable
public sealed class OdbcConnection : System.ComponentModel.Component, ICloneable, IDisposable, System.Data.IDbConnection
type OdbcConnection = class
    inherit DbConnection
    interface ICloneable
type OdbcConnection = class
    inherit Component
    interface ICloneable
    interface IDbConnection
    interface IDisposable
Public NotInheritable Class OdbcConnection
Inherits DbConnection
Implements ICloneable
Public NotInheritable Class OdbcConnection
Inherits Component
Implements ICloneable, IDbConnection, IDisposable
继承
OdbcConnection
继承
继承
实现

示例

下面的示例创建 OdbcCommandOdbcConnectionThe following example creates an OdbcCommand and an OdbcConnection. 将打开 OdbcConnection 并将其设置为 Connection 属性。The OdbcConnection is opened and set as the Connection property. 然后,该示例调用 ExecuteNonQuery,并关闭连接。The example then calls ExecuteNonQuery, and closes the connection. 为实现此目的,将向 ExecuteNonQuery 传递连接字符串和作为 SQL INSERT 语句的查询字符串。To accomplish this, the ExecuteNonQuery is passed a connection string and a query string that is an SQL INSERT statement.

static private void InsertRow(string connectionString)
{
    string queryString = 
        "INSERT INTO Customers (CustomerID, CompanyName) Values('NWIND', 'Northwind Traders')";
    OdbcCommand command = new OdbcCommand(queryString);

    using (OdbcConnection connection = new OdbcConnection(connectionString))
    {
        command.Connection = connection;
        connection.Open();
        command.ExecuteNonQuery();

        // The connection is automatically closed at 
        // the end of the Using block.
    }
}
Private Sub InsertRow(ByVal connectionString As String)

    Dim queryString As String = _
        "INSERT INTO Customers (CustomerID, CompanyName) Values('NWIND', 'Northwind Traders')"
    Dim command As New OdbcCommand(queryString)

    Using connection As New OdbcConnection(connectionString)
        command.Connection = connection
        connection.Open()
        command.ExecuteNonQuery()

        ' The connection is automatically closed at 
        ' the end of the Using block.
    End Using
End Sub

注解

OdbcConnection 对象表示与通过使用连接字符串或 ODBC 数据源名称(DSN)创建的数据源的唯一连接。An OdbcConnection object represents a unique connection to a data source created by using a connection string or ODBC data source name (DSN). 对于客户端/服务器数据库系统,它等效于到服务器的网络连接。With a client/server database system, it is equivalent to a network connection to the server. OdbcConnection 对象的某些方法或属性可能不可用,具体取决于本机 ODBC 驱动程序支持的功能。Depending on the functionality supported by the native ODBC driver, some methods or properties of an OdbcConnection object may not be available.

OdbcConnection 对象使用本机资源,如 ODBC 环境和连接句柄。The OdbcConnection object uses native resources such as ODBC environment and connection handles. 应始终通过在 OdbcConnection 对象超出范围之前调用 CloseDispose来显式关闭任何打开的 OdbcConnection 对象,或将连接置于 Using 语句中。You should always explicitly close any open OdbcConnection objects by calling Close or Dispose before the OdbcConnection object goes out of scope, or by placing the connection within a Using statement. 不这样做会使释放这些本机资源以进行垃圾回收。Not doing this leaves the freeing of these native resources to garbage collection. 它可能不会立即释放它们。It might not free them immediately. 这进而最终会导致底层驱动程序耗尽资源或达到最大限制。This, in turn, can eventually cause the underlying driver to run out of resources or reach a maximum limit. 这会导致间歇性故障。This has resulted in intermittent failures. 例如,你可能会遇到与 Maximum Connections 相关的错误,因为垃圾回收器有许多连接正在等待删除。For example, you might experience Maximum Connections -related errors while many connections are waiting to be deleted by the garbage collector. 通过显式关闭连接,可以更有效地使用本机资源,从而提高可伸缩性并提高应用程序的总体性能。Explicitly closing the connections allows for a more efficient use of native resources, enhancing scalability and improving overall application performance.

备注

若要部署高性能应用程序,你必须经常使用连接池。To deploy high-performance applications, you frequently must use connection pooling. 但是,当你使用适用于 ODBC 的 .NET Framework 数据提供程序时,你不必启用连接池,因为提供程序会自动管理此。However, when you use the .NET Framework Data Provider for ODBC, you do not have to enable connection pooling because the provider manages this automatically.

如果 OdbcCommand 类的 Execute 方法之一导致严重 OdbcException (例如,SQL Server 严重级别为20或更高),则 OdbcConnection 可能会关闭。If one of the Execute methods of the OdbcCommand class causes a fatal OdbcException (for example, a SQL Server severity level of 20 or greater), the OdbcConnection may close. 但是,用户可以重新打开连接并继续操作。However, the user can reopen the connection and continue.

创建 OdbcConnection 对象的实例的应用程序可以通过设置声明性或命令性安全要求,要求所有直接和间接调用方对代码具有足够的权限。An application that creates an instance of the OdbcConnection object can require all direct and indirect callers to have sufficient permission to the code by setting declarative or imperative security demands. OdbcConnection 使用 OdbcPermission 对象创建安全要求。OdbcConnection creates security demands by using the OdbcPermission object. 用户可以使用 OdbcPermissionAttribute 对象验证其代码是否具有足够的权限。Users can verify that their code has sufficient permissions by using the OdbcPermissionAttribute object. 用户和管理员还可以使用代码访问安全性策略工具(Caspol.exe)来修改计算机、用户和企业级别的安全策略。Users and administrators can also use the Code Access Security Policy Tool (Caspol.exe) to modify security policy at the computer, user, and enterprise levels. 有关更多信息,请参见 Code Access Security and ADO.NETFor more information, see Code Access Security and ADO.NET.

有关处理来自数据源的警告和信息性消息的详细信息,请参阅连接事件For more information about handling warning and informational messages from the data source, see Connection Events.

构造函数

OdbcConnection()

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

OdbcConnection(String)

使用指定的连接字符串初始化 OdbcConnection 类的新实例。Initializes a new instance of the OdbcConnection class with the specified connection string.

属性

CanRaiseEvents

获取一个指示组件是否可以引发事件的值。Gets a value indicating whether the component can raise an event.

(继承自 Component)
ConnectionString

获取或设置用于打开数据源的字符串。Gets or sets the string used to open a data source.

ConnectionTimeout

获取或设置在尝试建立连接时终止尝试并生成错误之前所等待的时间(以秒为单位)。Gets or sets the time to wait (in seconds) while trying to establish a connection before terminating the attempt and generating an error.

Container

获取包含 IContainerComponentGets the IContainer that contains the Component.

(继承自 Component)
Database

获取当前数据库的名称或打开连接后要使用的数据库的名称。Gets the name of the current database or the database to be used after a connection is opened.

DataSource

获取数据源的服务器名或文件名。Gets the server name or file name of the data source.

DbProviderFactory

获取此 DbProviderFactoryDbConnectionGets the DbProviderFactory for this DbConnection.

(继承自 DbConnection)
DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。Gets a value that indicates whether the Component is currently in design mode.

(继承自 Component)
Driver

获取为当前连接指定的 ODBC 驱动程序名称。Gets the name of the ODBC driver specified for the current connection.

Events

获取附加到此 Component 的事件处理程序的列表。Gets the list of event handlers that are attached to this Component.

(继承自 Component)
ServerVersion

获取一个包含客户端所连接到的服务器的版本的字符串。Gets a string that contains the version of the server to which the client is connected.

Site

获取或设置 ISiteComponentGets or sets the ISite of the Component.

(继承自 Component)
State

获取连接的当前状态。Gets the current state of the connection.

方法

BeginDbTransaction(IsolationLevel)

在派生类中重写时,启动数据库事务。When overridden in a derived class, starts a database transaction.

(继承自 DbConnection)
BeginDbTransactionAsync(IsolationLevel, CancellationToken)

异步启动数据库事务。Asynchronously starts a database transaction.

(继承自 DbConnection)
BeginTransaction()

在数据源中开始事务。Starts a transaction at the data source.

BeginTransaction(IsolationLevel)

在数据源中用指定的 IsolationLevel 值开始事务。Starts a transaction at the data source with the specified IsolationLevel value.

BeginTransactionAsync(CancellationToken)

异步开始数据库事务。Asynchronously begins a database transaction.

(继承自 DbConnection)
BeginTransactionAsync(IsolationLevel, CancellationToken)

异步开始数据库事务。Asynchronously begins a database transaction.

(继承自 DbConnection)
ChangeDatabase(String)

更改与打开的 OdbcConnection 关联的当前数据库。Changes the current database associated with an open OdbcConnection.

ChangeDatabaseAsync(String, CancellationToken)

为打开的连接对象异步更改当前数据库。Asynchronously changes the current database for an open connection.

(继承自 DbConnection)
Close()

关闭到数据源的连接。Closes the connection to the data source.

CloseAsync()

异步关闭与数据库之间的连接。Asynchronously closes the connection to the database.

(继承自 DbConnection)
CreateCommand()

创建并返回一个与该 OdbcCommand 关联的 OdbcConnection 对象。Creates and returns an OdbcCommand object associated with the OdbcConnection.

CreateDbCommand()

在派生类中重写时,创建并返回与当前连接关联的 DbCommand 对象。When overridden in a derived class, creates and returns a DbCommand object associated with the current connection.

(继承自 DbConnection)
CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(继承自 MarshalByRefObject)
Dispose()

释放由 Component 使用的所有资源。Releases all resources used by the Component.

(继承自 Component)
Dispose(Boolean)

释放由 Component 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(继承自 Component)
DisposeAsync()

异步处置连接对象。Asynchronously diposes the connection object.

(继承自 DbConnection)
EnlistDistributedTransaction(ITransaction)

在指定的事务中登记为分布式事务。Enlists in the specified transaction as a distributed transaction.

EnlistTransaction(Transaction)

在指定的事务中登记为分布式事务。Enlists in the specified transaction as a distributed transaction.

Equals(Object)

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

(继承自 Object)
GetHashCode()

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

(继承自 Object)
GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(继承自 MarshalByRefObject)
GetSchema()

返回此 OdbcConnection 的数据源的架构信息。Returns schema information for the data source of this OdbcConnection.

GetSchema(String)

使用架构名称的指定名称,返回此 OdbcConnection 的数据源的架构信息。Returns schema information for the data source of this OdbcConnection using the specified name for the schema name.

GetSchema(String, String[])

通过使用指定字符串作为架构名称,指定字符串数组作为限制值,返回此 OdbcConnection 的数据源的架构信息。Returns schema information for the data source of this OdbcConnection using the specified string for the schema name and the specified string array for the restriction values.

GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。Returns an object that represents a service provided by the Component or by its Container.

(继承自 Component)
GetType()

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

(继承自 Object)
InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(继承自 MarshalByRefObject)
MemberwiseClone()

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

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(继承自 MarshalByRefObject)
OnStateChange(StateChangeEventArgs)

引发 StateChange 事件。Raises the StateChange event.

(继承自 DbConnection)
Open()

使用 ConnectionString 指定的属性设置打开到数据源的连接。Opens a connection to a data source with the property settings specified by the ConnectionString.

OpenAsync()

Open()的异步版本,打开由 ConnectionString指定的设置的数据库连接。An asynchronous version of Open(), which opens a database connection with the settings specified by the ConnectionString. 此方法通过 CancellationToken.None 调用虚拟方法 OpenAsync(CancellationToken)This method invokes the virtual method OpenAsync(CancellationToken) with CancellationToken.None.

(继承自 DbConnection)
OpenAsync(CancellationToken)

这是 Open() 的异步版本。This is the asynchronous version of Open(). 提供程序应使用合适的实现进行重写。Providers should override with an appropriate implementation. 可选择性接受取消标记。The cancellation token can optionally be honored.

默认实现调用同步 Open() 调用并返回已完成任务。The default implementation invokes the synchronous Open() call and returns a completed task. 如果传递到已取消的取消标记,则默认实现将返回已取消的 cancellationToken。The default implementation will return a cancelled task if passed an already cancelled cancellationToken. Open 引发的异常将通过返回的任务异常属性传递。Exceptions thrown by Open will be communicated via the returned Task Exception property.

在返回的任务完成前,不要调用 DbConnection 对象的其他方法和属性。Do not invoke other methods and properties of the DbConnection object until the returned Task is complete.

(继承自 DbConnection)
ReleaseObjectPool()

指示当释放最后的基础连接时可以释放 ODBC 驱动程序管理器环境句柄。Indicates that the ODBC Driver Manager environment handle can be released when the last underlying connection is released.

ToString()

返回包含 String 的名称的 Component(如果有)。Returns a String containing the name of the Component, if any. 不应重写此方法。This method should not be overridden.

(继承自 Component)

事件

Disposed

在通过调用 Dispose() 方法释放组件时发生。Occurs when the component is disposed by a call to the Dispose() method.

(继承自 Component)
InfoMessage

在 ODBC 驱动程序发送警告或信息性消息时发生。Occurs when the ODBC driver sends a warning or an informational message.

StateChange

当连接状态改变时发生。Occurs when the state of the connection changes.

显式接口实现

ICloneable.Clone()

有关此成员的说明,请参阅 Clone()For a description of this member, see Clone().

IDbConnection.BeginTransaction()

开始一项数据库事务。Begins a database transaction.

IDbConnection.BeginTransaction(IsolationLevel)

以指定的隔离级别启动数据库事务。Begins a database transaction with the specified isolation level.

IDbConnection.CreateCommand()

创建并返回与连接关联的命令对象。Creates and returns a command object associated with the connection.

适用于

另请参阅