IDbConnection 인터페이스

정의

데이터 소스에 대한 열린 연결을 나타내며 관계형 데이터베이스에 액세스하는 .NET 데이터 공급자에 의해 구현됩니다.

public interface class IDbConnection : IDisposable
public interface IDbConnection : IDisposable
type IDbConnection = interface
    interface IDisposable
Public Interface IDbConnection
Implements IDisposable
파생
구현

예제

다음 예제에서는 파생된 클래스의 인스턴스를 만듭니다 SqlCommandSqlConnection입니다. SqlConnection 열고로 설정 합니다 Connection 에 대 한는 SqlCommand. 이 예제에서는 호출 ExecuteNonQuery, 연결을 닫습니다. 이 수행 하는 ExecuteNonQuery 연결 문자열 및 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

설명

IDbConnection 인터페이스는 데이터 원본 (예를 들어 서버에 네트워크 연결)를 사용 하 여 고유한 세션을 나타내는 연결 클래스를 구현 하는 상속 클래스를 사용 합니다. 연결 클래스에 대 한 자세한 내용은 참조 하세요. 데이터 원본에 연결할합니다.

애플리케이션의 인스턴스를 만들지 않습니다 합니다 IDbConnection 인터페이스를 직접 상속 된 클래스의 인스턴스를 만들고 있지만 IDbConnection합니다.

상속 된 클래스 IDbConnection 상속 된 모든 멤버를 구현 하 고 일반적으로 공급자 특정 기능을 추가 하기 위한 추가 멤버를 정의 해야 합니다. 예를 들어 합니다 IDbConnection 인터페이스를 정의 합니다 ConnectionTimeout 속성입니다. 차례로 합니다 SqlConnection 클래스는이 속성을 상속 하 고도 정의 합니다 PacketSize 속성입니다.

구현자 참고

.NET Framework 데이터 공급자 간의 일관성을 높이기 위해 상속 클래스의 이름을 형식 PrvClassname 으로 지정합니다. 여기서 Prv 는 특정 .NET Framework 데이터 공급자 네임스페이스의 모든 클래스에 지정된 균일한 접두사입니다. 예를 들어 Sql 접두사입니다 합니다 SqlConnection 클래스는 System.Data.SqlClient 네임 스페이스입니다.

상속 하는 경우는 IDbConnection 인터페이스 다음 생성자를 구현 해야 합니다.

항목 설명
PrvConnection() PrvConnection 클래스의 새 instance 초기화합니다.
PrvConnection(string connectionString) 연결 문자열 포함하는 문자열이 제공되면 PrvConnection 클래스의 새 instance 초기화합니다.

속성

ConnectionString

데이터베이스를 여는 데 사용되는 문자열을 가져오거나 설정합니다.

ConnectionTimeout

시도를 종료하고 오류를 생성하기 전에 연결하는 동안 대기할 시간(초 단위)을 가져옵니다.

Database

현재 데이터베이스 이름이나 연결이 열린 후 사용할 데이터베이스의 이름을 가져옵니다.

State

연결의 현재 상태를 가져옵니다.

메서드

BeginTransaction()

데이터베이스 트랜잭션을 시작합니다.

BeginTransaction(IsolationLevel)

지정된 IsolationLevel 값을 사용하여 데이터베이스 트랜잭션을 시작합니다.

ChangeDatabase(String)

열려 있는 Connection 개체의 현재 데이터베이스를 변경합니다.

Close()

데이터베이스에 대한 연결을 닫습니다.

CreateCommand()

연결과 관련된 Command 개체를 만들고 반환합니다.

Dispose()

관리되지 않는 리소스의 확보, 해제 또는 다시 설정과 관련된 애플리케이션 정의 작업을 수행합니다.

(다음에서 상속됨 IDisposable)
Open()

공급자별 Connection 개체의 ConnectionString 속성으로 지정된 설정을 사용하여 데이터베이스 연결을 엽니다.

적용 대상