IDbConnection IDbConnection IDbConnection IDbConnection Interface

定义

表示一个与数据源的开放连接,并由访问关系数据库的 .NET Framework 数据提供程序实现。Represents an open connection to a data source, and is implemented by .NET Framework data providers that access relational databases.

public interface class IDbConnection : IDisposable
public interface IDbConnection : IDisposable
type IDbConnection = interface
    interface IDisposable
Public Interface IDbConnection
Implements IDisposable
派生
实现

示例

下面的示例创建派生类SqlCommandSqlConnection的实例。The following example creates instances of the derived classes, SqlCommand and SqlConnection. 打开并将设置ConnectionSqlCommand的。 SqlConnectionThe SqlConnection is opened and set as the Connection for the SqlCommand. 然后, 该示例ExecuteNonQuery调用并关闭连接。The example then calls ExecuteNonQuery, and closes the connection. 为实现此目的, ExecuteNonQuery传递了一个连接字符串和一个查询字符串, 后者是 transact-sql INSERT 语句。To accomplish this, the ExecuteNonQuery is passed a connection string and a query string that is a Transact-SQL INSERT statement.

using System;
using System.Data;

namespace IDbConnectionSample {
   class Program {
      static void Main(string[] args) {
         IDbConnection connection;

         // First use a SqlClient connection
         connection = new System.Data.SqlClient.SqlConnection(@"Server=(localdb)\V11.0");
         Console.WriteLine("SqlClient\r\n{0}", GetServerVersion(connection));
         connection = new System.Data.SqlClient.SqlConnection(@"Server=(local);Integrated Security=true");
         Console.WriteLine("SqlClient\r\n{0}", GetServerVersion(connection));

         // Call the same method using ODBC
         // NOTE: LocalDB requires the SQL Server 2012 Native Client ODBC driver
         connection = new System.Data.Odbc.OdbcConnection(@"Driver={SQL Server Native Client 11.0};Server=(localdb)\v11.0");
         Console.WriteLine("ODBC\r\n{0}", GetServerVersion(connection));
         connection = new System.Data.Odbc.OdbcConnection(@"Driver={SQL Server Native Client 11.0};Server=(local);Trusted_Connection=yes");
         Console.WriteLine("ODBC\r\n{0}", GetServerVersion(connection));

         // Call the same method using OLE DB
         connection = new System.Data.OleDb.OleDbConnection(@"Provider=SQLNCLI11;Server=(localdb)\v11.0;Trusted_Connection=yes;");
         Console.WriteLine("OLE DB\r\n{0}", GetServerVersion(connection));
         connection = new System.Data.OleDb.OleDbConnection(@"Provider=SQLNCLI11;Server=(local);Trusted_Connection=yes;");
         Console.WriteLine("OLE DB\r\n{0}", GetServerVersion(connection));
         }

      public static string GetServerVersion(IDbConnection connection) {
         // Ensure that the connection is opened (otherwise executing the command will fail)
         ConnectionState originalState = connection.State;
         if (originalState != ConnectionState.Open)
            connection.Open();
         try {
            // Create a command to get the server version
            // NOTE: The query's syntax is SQL Server specific
            IDbCommand command = connection.CreateCommand();
            command.CommandText = "SELECT @@version";
            return (string)command.ExecuteScalar();
         }
         finally {
            // Close the connection if that's how we got it
            if (originalState == ConnectionState.Closed)
               connection.Close();
         }
      }
   }
}
Imports System.Data

Class Program

    Public Shared Sub Main(args As String())

        Dim connection As IDbConnection



        ' First use a SqlClient connection

        connection = New System.Data.SqlClient.SqlConnection("Server=(localdb)\V11.0")

        Console.WriteLine("SqlClient" & vbCr & vbLf & "{0}", GetServerVersion(connection))

        connection = New System.Data.SqlClient.SqlConnection("Server=(local);Integrated Security=true")

        Console.WriteLine("SqlClient" & vbCr & vbLf & "{0}", GetServerVersion(connection))



        ' Call the same method using ODBC

        ' NOTE: LocalDB requires the SQL Server 2012 Native Client ODBC driver

        connection = New System.Data.Odbc.OdbcConnection("Driver={SQL Server Native Client 11.0};Server=(localdb)\v11.0")

        Console.WriteLine("ODBC" & vbCr & vbLf & "{0}", GetServerVersion(connection))

        connection = New System.Data.Odbc.OdbcConnection("Driver={SQL Server Native Client 11.0};Server=(local);Trusted_Connection=yes")

        Console.WriteLine("ODBC" & vbCr & vbLf & "{0}", GetServerVersion(connection))


        ' Call the same method using OLE DB

        connection = New System.Data.OleDb.OleDbConnection("Provider=SQLNCLI11;Server=(localdb)\v11.0;Trusted_Connection=yes;")

        Console.WriteLine("OLE DB" & vbCr & vbLf & "{0}", GetServerVersion(connection))

        connection = New System.Data.OleDb.OleDbConnection("Provider=SQLNCLI11;Server=(local);Trusted_Connection=yes;")

        Console.WriteLine("OLE DB" & vbCr & vbLf & "{0}", GetServerVersion(connection))

    End Sub



    Public Shared Function GetServerVersion(connection As IDbConnection) As String

        ' Ensure that the connection is opened (otherwise executing the command will fail)

        Dim originalState As ConnectionState = connection.State

        If originalState <> ConnectionState.Open Then

            connection.Open()

        End If

        Try

            ' Create a command to get the server version

            ' NOTE: The query's syntax is SQL Server specific

            Dim command As IDbCommand = connection.CreateCommand()

            command.CommandText = "SELECT @@version"

            Return DirectCast(command.ExecuteScalar(), String)

        Finally

            ' Close the connection if that's how we got it

            If originalState = ConnectionState.Closed Then

                connection.Close()

            End If

        End Try

    End Function

End Class

注解

IDbConnection接口允许继承类实现连接类, 该类表示与数据源的唯一会话 (例如, 与服务器的网络连接)。The IDbConnection interface enables an inheriting class to implement a Connection class, which represents a unique session with a data source (for example, a network connection to a server). 有关连接类的详细信息, 请参阅连接到数据源For more information about Connection classes, see Connecting to a Data Source.

应用程序不会直接创建IDbConnection接口的实例, 而是创建继承IDbConnection的类的实例。An application does not create an instance of the IDbConnection interface directly, but creates an instance of a class that inherits IDbConnection.

继承IDbConnection的类必须实现所有继承成员, 并且通常定义其他成员来添加特定于提供程序的功能。Classes that inherit IDbConnection must implement all inherited members, and typically define additional members to add provider-specific functionality. 例如, IDbConnection接口ConnectionTimeout定义属性。For example, the IDbConnection interface defines the ConnectionTimeout property. 反过来, SqlConnection该类继承此属性, 并且还PacketSize定义属性。In turn, the SqlConnection class inherits this property, and also defines the PacketSize property.

实施者说明

若要提升 .NET Framework 数据提供程序之间的一致性, 请将PrvClassname继承类命名为, 其中Prv是为特定 .NET Framework 数据提供程序命名空间中的所有类指定的统一前缀。To promote consistency among .NET Framework data providers, name the inheriting class in the form PrvClassname where Prv is the uniform prefix given to all classes in a specific .NET Framework data provider namespace. 例如, SqlSystem.Data.SqlClient命名空间中SqlConnection类的前缀。For example, Sql is the prefix of the SqlConnection class in the System.Data.SqlClient namespace.

IDbConnection接口继承时, 应实现以下构造函数:When you inherit from the IDbConnection interface, you should implement the following constructors:

Item 说明Description
PrvConnection()PrvConnection() 初始化 PrvConnection 类的新实例。Initializes a new instance of the PrvConnection class.

PrvConnection (字符串 connectionString)PrvConnection(string connectionString) 给定包含连接字符串的字符串时, 初始化 PrvConnection 类的新实例。Initializes a new instance of the PrvConnection class when given a string containing the connection string.

属性

ConnectionString ConnectionString ConnectionString ConnectionString

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

ConnectionTimeout ConnectionTimeout ConnectionTimeout ConnectionTimeout

获取终止尝试并生成错误之前在尝试建立连接时所等待的时间。Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error.

Database Database Database Database

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

State State State State

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

方法

BeginTransaction() BeginTransaction() BeginTransaction() BeginTransaction()

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

BeginTransaction(IsolationLevel) BeginTransaction(IsolationLevel) BeginTransaction(IsolationLevel) BeginTransaction(IsolationLevel)

以指定的 IsolationLevel 值开始数据库事务。Begins a database transaction with the specified IsolationLevel value.

ChangeDatabase(String) ChangeDatabase(String) ChangeDatabase(String) ChangeDatabase(String)

更改已打开的 Connection 对象的当前数据库。Changes the current database for an open Connection object.

Close() Close() Close() Close()

关闭与数据库之间的连接。Closes the connection to the database.

CreateCommand() CreateCommand() CreateCommand() CreateCommand()

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

Dispose() Dispose() Dispose() Dispose()

执行与释放或重置非托管资源关联的应用程序定义的任务。Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

(Inherited from IDisposable)
Open() Open() Open() Open()

打开具有指定设置(由特定于提供程序的 Connection 对象的 ConnectionString 属性所指定)的数据库连接。Opens a database connection with the settings specified by the ConnectionString property of the provider-specific Connection object.

适用于