IDbConnection Antarmuka

Definisi

Mewakili koneksi terbuka ke sumber data, dan diimplementasikan oleh penyedia data .NET yang mengakses database relasional.

public interface class IDbConnection : IDisposable
public interface IDbConnection : IDisposable
type IDbConnection = interface
    interface IDisposable
Public Interface IDbConnection
Implements IDisposable
Turunan
Penerapan

Contoh

Contoh berikut membuat instans kelas turunan, SqlCommand dan SqlConnection. SqlConnection dibuka dan ditetapkan sebagai Connection untuk SqlCommand. Contoh kemudian memanggil ExecuteNonQuery, dan menutup koneksi. Untuk mencapai hal ini, ExecuteNonQuery diteruskan string koneksi dan string kueri yang merupakan pernyataan TRANSACT-SQL INSERT.

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

Keterangan

Antarmuka IDbConnection memungkinkan kelas pewarisan untuk mengimplementasikan kelas Koneksi, yang mewakili sesi unik dengan sumber data (misalnya, koneksi jaringan ke server). Untuk informasi selengkapnya tentang kelas Koneksi, lihat Menyambungkan ke Sumber Data.

Aplikasi tidak membuat instans IDbConnection antarmuka secara langsung, tetapi membuat instans kelas yang mewarisi IDbConnection.

Kelas yang mewarisi IDbConnection harus mengimplementasikan semua anggota yang diwariskan, dan biasanya menentukan anggota tambahan untuk menambahkan fungsionalitas khusus penyedia. Misalnya, IDbConnection antarmuka menentukan ConnectionTimeout properti . Pada gilirannya SqlConnection , kelas mewarisi properti ini, dan juga menentukan PacketSize properti .

Catatan Bagi Implementer

Untuk mempromosikan konsistensi di antara penyedia data .NET Framework, beri nama kelas pewarisan dalam bentuk PrvClassname di mana Prv adalah awalan seragam yang diberikan kepada semua kelas di namespace layanan penyedia data .NET Framework tertentu. Misalnya, Sql adalah awalan SqlConnection kelas di System.Data.SqlClient namespace layanan.

Saat mewarisi dari IDbConnection antarmuka, Anda harus mengimplementasikan konstruktor berikut:

Item Deskripsi
PrvConnection() Menginisialisasi instans baru kelas PrvConnection.
PrvConnection(string connectionString) Menginisialisasi instans baru kelas PrvConnection saat diberikan string yang berisi string koneksi.

Properti

ConnectionString

Mendapatkan atau mengatur string yang digunakan untuk membuka database.

ConnectionTimeout

Mendapatkan waktu untuk menunggu (dalam detik) saat mencoba membuat koneksi sebelum mengakhiri upaya dan menghasilkan kesalahan.

Database

Mendapatkan nama database saat ini atau database yang akan digunakan setelah koneksi dibuka.

State

Mendapatkan status koneksi saat ini.

Metode

BeginTransaction()

Memulai transaksi database.

BeginTransaction(IsolationLevel)

Memulai transaksi database dengan nilai yang ditentukan IsolationLevel .

ChangeDatabase(String)

Mengubah database saat ini untuk objek terbuka Connection .

Close()

Menutup koneksi ke database.

CreateCommand()

Membuat dan mengembalikan objek Perintah yang terkait dengan koneksi.

Dispose()

Melakukan tugas yang ditentukan aplikasi yang terkait dengan membebaskan, melepaskan, atau mereset sumber daya yang tidak terkelola.

(Diperoleh dari IDisposable)
Open()

Membuka koneksi database dengan pengaturan yang ditentukan oleh ConnectionString properti objek Koneksi khusus penyedia.

Berlaku untuk