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
派生
实现

示例

下面的示例创建的派生类的实例SqlCommandSqlConnectionThe following example creates instances of the derived classes, SqlCommand and SqlConnection. SqlConnection打开,并设置为ConnectionSqlCommandThe 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接口,用于实现 Connection 类,表示与数据源 (例如,网络连接到服务器) 的唯一会话的继承类。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接口直接,但创建继承的类的实例IDbConnectionAn 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. 例如,Sql的前缀SqlConnection类中System.Data.SqlClient命名空间。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.

适用于