IDbConnection Interface
Definição
Representa uma conexão aberta com uma fonte de dados, e é implementada por provedores de dados .NET que acessam bancos de dados relacionais.Represents an open connection to a data source, and is implemented by .NET 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
- Derivado
- Implementações
Exemplos
O exemplo a seguir cria instâncias das classes derivadas SqlCommand e SqlConnection .The following example creates instances of the derived classes, SqlCommand and SqlConnection. O SqlConnection é aberto e definido como o Connection para o SqlCommand .The SqlConnection is opened and set as the Connection for the SqlCommand. Em seguida, o exemplo chama ExecuteNonQuery e fecha a conexão.The example then calls ExecuteNonQuery, and closes the connection. Para fazer isso, o ExecuteNonQuery é passado uma cadeia de conexão e uma cadeia de caracteres de consulta que é uma instrução INSERT do Transact-SQL.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
Comentários
A IDbConnection interface permite que uma classe herdada implemente uma classe Connection, que representa uma sessão exclusiva com uma fonte de dados (por exemplo, uma conexão de rede com um servidor).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). Para obter mais informações sobre classes de conexão, consulte conectando-se a uma fonte de dados.For more information about Connection classes, see Connecting to a Data Source.
Um aplicativo não cria uma instância da IDbConnection interface diretamente, mas cria uma instância de uma classe que herda IDbConnection .An application does not create an instance of the IDbConnection interface directly, but creates an instance of a class that inherits IDbConnection.
As classes que herdam IDbConnection devem implementar todos os membros herdados e geralmente definem membros adicionais para adicionar funcionalidade específica do provedor.Classes that inherit IDbConnection must implement all inherited members, and typically define additional members to add provider-specific functionality. Por exemplo, a IDbConnection interface define a ConnectionTimeout propriedade.For example, the IDbConnection interface defines the ConnectionTimeout property. Por sua vez, a SqlConnection classe herda essa propriedade e também define a PacketSize propriedade.In turn, the SqlConnection class inherits this property, and also defines the PacketSize property.
Notas aos Implementadores
Para promover a consistência entre .NET Framework provedores de dados, nomeie a classe herdeira no formulário PrvClassname
em que Prv
é o prefixo uniforme fornecido a todas as classes em um namespace de provedor de dados .NET Framework específico.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. Por exemplo, Sql
é o prefixo da SqlConnection classe no System.Data.SqlClient
namespace.For example, Sql
is the prefix of the SqlConnection class in the System.Data.SqlClient
namespace.
Ao herdar da IDbConnection interface, você deve implementar os seguintes construtores:When you inherit from the IDbConnection interface, you should implement the following constructors:
ItemItem | DescriçãoDescription |
---|---|
PrvConnection()PrvConnection() | Inicializa uma nova instância da classe PrvConnection.Initializes a new instance of the PrvConnection class. |
PrvConnection (cadeia de caracteres connectionString)PrvConnection(string connectionString) | Inicializa uma nova instância da classe PrvConnection quando uma cadeia de caracteres que contém a cadeia de conexão é fornecida.Initializes a new instance of the PrvConnection class when given a string containing the connection string. |
Propriedades
ConnectionString |
Obtém ou define a cadeia de caracteres usada para abrir um banco de dados.Gets or sets the string used to open a database. |
ConnectionTimeout |
Obtém o tempo de espera (em segundos) durante a tentativa de estabelecimento da conexão antes que a tentativa seja terminada e um erro seja gerado.Gets the time to wait (in seconds) while trying to establish a connection before terminating the attempt and generating an error. |
Database |
Obtém o nome do banco de dados atual ou o banco de dados a ser usado após uma conexão ser aberta.Gets the name of the current database or the database to be used after a connection is opened. |
State |
Obtém o estado atual da conexão.Gets the current state of the connection. |
Métodos
BeginTransaction() |
Inicia uma transação de banco de dados.Begins a database transaction. |
BeginTransaction(IsolationLevel) |
Inicia uma transação de banco de dados com o valor IsolationLevel especificado.Begins a database transaction with the specified IsolationLevel value. |
ChangeDatabase(String) |
Altera o banco de dados atual para um objeto |
Close() |
Fecha a conexão com o banco de dados.Closes the connection to the database. |
CreateCommand() |
Cria e retorna um objeto de comando associado à conexão.Creates and returns a Command object associated with the connection. |
Dispose() |
Realiza tarefas definidas pelo aplicativo associadas à liberação ou à redefinição de recursos não gerenciados.Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. (Herdado de IDisposable) |
Open() |
Abre uma conexão de banco de dados com as configurações especificadas pela propriedade |