SqlConnection Construtores

Definição

Inicializa uma nova instância da classe SqlConnection.Initializes a new instance of the SqlConnection class.

Sobrecargas

SqlConnection()

Inicializa uma nova instância da classe SqlConnection.Initializes a new instance of the SqlConnection class.

SqlConnection(String)

Inicializa uma nova instância da classe SqlConnection quando recebe uma cadeia de caracteres que contém a cadeia de conexão.Initializes a new instance of the SqlConnection class when given a string that contains the connection string.

SqlConnection(String, SqlCredential)

Inicializa uma nova instância da classe SqlConnection que recebeu uma cadeia de conexão, que não usa Integrated Security = true e um objeto SqlCredential que contém a ID de usuário e senha.Initializes a new instance of the SqlConnection class given a connection string, that does not use Integrated Security = true and a SqlCredential object that contains the user ID and password.

SqlConnection()

Inicializa uma nova instância da classe SqlConnection.Initializes a new instance of the SqlConnection class.

public:
 SqlConnection();
public SqlConnection ();
Public Sub New ()

Exemplos

O exemplo a seguir cria e abre uma SqlConnection.The following example creates and opens a SqlConnection.

private static void OpenSqlConnection()
{
    string connectionString = GetConnectionString();
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
        Console.WriteLine("State: {0}", connection.State);
    }
}

static private string GetConnectionString()
{
    // To avoid storing the connection string in your code, 
    // you can retrieve it from a configuration file, using the 
    // System.Configuration.ConfigurationManager.ConnectionStrings property 
    return "Data Source=(local);Initial Catalog=AdventureWorks;"
        + "Integrated Security=SSPI;";
}
Private Sub OpenSqlConnection()
    Dim connectionString As String = GetConnectionString()
    Using connection As New SqlConnection(connectionString)
        connection.Open()
        Console.WriteLine("ServerVersion: {0}", connection.ServerVersion)
        Console.WriteLine("State: {0}", connection.State)
    End Using
End Sub

Private Function GetConnectionString() As String
    ' To avoid storing the connection string in your code,  
    ' you can retrieve it from a configuration file, using the
    ' System.Configuration.ConfigurationManager.ConnectionStrings property
    Return "Data Source=(local);Database=AdventureWorks;" _
      & "Integrated Security=SSPI;"
End Function

Comentários

Quando uma nova instância de SqlConnection é criada, as propriedades de leitura/gravação são definidas com os valores iniciais a seguir, a menos que sejam definidas especificamente usando suas palavras-chave associadas na propriedade ConnectionString.When a new instance of SqlConnection is created, the read/write properties are set to the following initial values unless they are specifically set using their associated keywords in the ConnectionString property.

{1>Propriedades<1}Properties Valor inicialInitial value
ConnectionString Cadeia de caracteres vazia ("")empty string ("")
ConnectionTimeout 1515
Database Cadeia de caracteres vazia ("")empty string ("")
DataSource Cadeia de caracteres vazia ("")empty string ("")

Você pode alterar o valor dessas propriedades somente usando a propriedade ConnectionString.You can change the value for these properties only by using the ConnectionString property. A classe SqlConnectionStringBuilder fornece funcionalidade para criar e gerenciar o conteúdo de cadeias de conexão.The SqlConnectionStringBuilder class provides functionality for creating and managing the contents of connection strings.

Veja também

SqlConnection(String)

Inicializa uma nova instância da classe SqlConnection quando recebe uma cadeia de caracteres que contém a cadeia de conexão.Initializes a new instance of the SqlConnection class when given a string that contains the connection string.

public:
 SqlConnection(System::String ^ connectionString);
public SqlConnection (string connectionString);
new System.Data.SqlClient.SqlConnection : string -> System.Data.SqlClient.SqlConnection
Public Sub New (connectionString As String)

Parâmetros

connectionString
String

A conexão usada para abrir o banco de dados do SQL Server.The connection used to open the SQL Server database.

Exemplos

O exemplo a seguir cria e abre uma SqlConnection.The following example creates and opens a SqlConnection.

private static void OpenSqlConnection()
{
    string connectionString = GetConnectionString();

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        Console.WriteLine("State: {0}", connection.State);
        Console.WriteLine("ConnectionString: {0}",
            connection.ConnectionString);
    }
}

static private string GetConnectionString()
{
    // To avoid storing the connection string in your code, 
    // you can retrieve it from a configuration file, using the 
    // System.Configuration.ConfigurationSettings.AppSettings property 
    return "Data Source=(local);Initial Catalog=AdventureWorks;"
        + "Integrated Security=SSPI;";
}
Private Sub OpenSqlConnection()
    Dim connectionString As String = GetConnectionString()

    Using connection As New SqlConnection(connectionString)

        connection.Open()

        Console.WriteLine("State: {0}", connection.State)
        Console.WriteLine("ConnectionString: {0}", _
            connection.ConnectionString)
    End Using
End Sub

Private Function GetConnectionString() As String
    ' To avoid storing the connection string in your code,  
    ' you can retrieve it from a configuration file, using the
    ' System.Configuration.ConfigurationSettings.AppSettings property
    Return "Data Source=(local);Database=AdventureWorks;" _
      & "Integrated Security=SSPI;"
End Function

Comentários

Quando uma nova instância de SqlConnection é criada, as propriedades de leitura/gravação são definidas com os valores iniciais a seguir, a menos que sejam definidas especificamente usando suas palavras-chave associadas na propriedade ConnectionString.When a new instance of SqlConnection is created, the read/write properties are set to the following initial values unless they are specifically set using their associated keywords in the ConnectionString property.

{1>Propriedades<1}Properties Valor inicialInitial value
ConnectionString connectionString
ConnectionTimeout 1515
Database Cadeia de caracteres vazia ("")empty string ("")
DataSource Cadeia de caracteres vazia ("")empty string ("")

Você pode alterar o valor dessas propriedades somente usando a propriedade ConnectionString.You can change the value for these properties only by using the ConnectionString property. A classe SqlConnection fornece funcionalidade para criar e gerenciar o conteúdo de cadeias de conexão.The SqlConnection class provides functionality for creating and managing the contents of connection strings.

Veja também

SqlConnection(String, SqlCredential)

Inicializa uma nova instância da classe SqlConnection que recebeu uma cadeia de conexão, que não usa Integrated Security = true e um objeto SqlCredential que contém a ID de usuário e senha.Initializes a new instance of the SqlConnection class given a connection string, that does not use Integrated Security = true and a SqlCredential object that contains the user ID and password.

public:
 SqlConnection(System::String ^ connectionString, System::Data::SqlClient::SqlCredential ^ cred);
public SqlConnection (string connectionString, System.Data.SqlClient.SqlCredential cred);
new System.Data.SqlClient.SqlConnection : string * System.Data.SqlClient.SqlCredential -> System.Data.SqlClient.SqlConnection
Public Sub New (connectionString As String, cred As SqlCredential)

Parâmetros

connectionString
String

Uma cadeia de conexão que não usa nenhuma das seguintes palavras-chave da cadeia de conexão: Integrated Security = true, UserId ou Password; ou que não usa ContextConnection = true.A connection string that does not use any of the following connection string keywords: Integrated Security = true, UserId, or Password; or that does not use ContextConnection = true.

credential
SqlCredential

Um objeto SqlCredential.A SqlCredential object. Se credential for nulo, SqlConnection(String, SqlCredential) será funcionalmente equivalente ao SqlConnection(String).If credential is null, SqlConnection(String, SqlCredential) is functionally equivalent to SqlConnection(String).

Veja também

Aplica-se a