IDbConnection 介面

定義

代表連至資料來源的開放連線,而且是由存取關聯式資料庫的 .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,並將其設定為 SqlCommandConnectionThe SqlConnection is opened and set as the Connection for the SqlCommand. 然後,此範例會呼叫 ExecuteNonQuery,並關閉連接。The example then calls ExecuteNonQuery, and closes the connection. 為達成此目的,會傳遞一個連接字串和一個查詢字串做為 Transact-sql INSERT 語句的 ExecuteNonQueryTo 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 Data Provider 命名空間中所有類別的統一前置詞。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

取得或設定用來開啟資料庫的字串。Gets or sets the string used to open a database.

ConnectionTimeout

取得在終止嘗試並產生錯誤前嘗試建立連接的等待時間 (以秒為單位)。Gets the time to wait (in seconds) while trying to establish a connection before terminating the attempt and generating an error.

Database

取得目前資料庫或要在連接開啟之後使用的資料庫名稱。Gets the name of the current database or the database to be used after a connection is opened.

State

取得連線目前的狀態。Gets the current state of the connection.

方法

BeginTransaction()

開始資料庫交易。Begins a database transaction.

BeginTransaction(IsolationLevel)

使用指定的 IsolationLevel 值來開始資料庫交易。Begins a database transaction with the specified IsolationLevel value.

ChangeDatabase(String)

為開啟的 Connection 物件變更目前的資料庫。Changes the current database for an open Connection object.

Close()

關閉與資料庫的連接。Closes the connection to the database.

CreateCommand()

建立並傳回與連接相關聯的 Command 物件。Creates and returns a Command object associated with the connection.

Dispose()

執行與釋放 (Free)、釋放 (Release) 或重設 Unmanaged 資源相關聯之應用程式定義的工作。Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

(繼承來源 IDisposable)
Open()

使用提供者特定 Connection 物件的 ConnectionString 屬性所指定的設定來開啟資料庫連接。Opens a database connection with the settings specified by the ConnectionString property of the provider-specific Connection object.

適用於