SqlConnection Constructores

Definición

Inicializa una nueva instancia de la clase SqlConnection.Initializes a new instance of the SqlConnection class.

Sobrecargas

SqlConnection()

Inicializa una nueva instancia de la clase SqlConnection.Initializes a new instance of the SqlConnection class.

SqlConnection(String)

Inicializa una nueva instancia de la clase SqlConnection, dada una cadena que contiene la cadena de conexión.Initializes a new instance of the SqlConnection class when given a string that contains the connection string.

SqlConnection(String, SqlCredential)

Inicializa una nueva instancia de la clase SqlConnection a la que se proporciona una cadena de conexión que no usa Integrated Security = true y un objeto SqlCredential que contiene el identificador de usuario y la contraseña.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 una nueva instancia de la clase SqlConnection.Initializes a new instance of the SqlConnection class.

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

Ejemplos

En el ejemplo siguiente se crea y se abre un 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

Comentarios

Cuando se crea una nueva instancia de SqlConnection, las propiedades de lectura y escritura se establecen en los valores iniciales siguientes, a menos que se establezcan específicamente usando sus palabras clave asociadas en la propiedad 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.

PropiedadesProperties Valor inicialInitial value
ConnectionString cadena vacía ("")empty string ("")
ConnectionTimeout 1515
Database cadena vacía ("")empty string ("")
DataSource cadena vacía ("")empty string ("")

Solo puede cambiar el valor de estas propiedades mediante la propiedad ConnectionString.You can change the value for these properties only by using the ConnectionString property. La clase SqlConnectionStringBuilder proporciona funcionalidad para crear y administrar el contenido de las cadenas de conexión.The SqlConnectionStringBuilder class provides functionality for creating and managing the contents of connection strings.

Consulte también:

SqlConnection(String)

Inicializa una nueva instancia de la clase SqlConnection, dada una cadena que contiene la cadena de conexión.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

Conexión usada para abrir la base de datos de SQL Server.The connection used to open the SQL Server database.

Ejemplos

En el ejemplo siguiente se crea y se abre un 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

Comentarios

Cuando se crea una nueva instancia de SqlConnection, las propiedades de lectura y escritura se establecen en los valores iniciales siguientes, a menos que se establezcan específicamente usando sus palabras clave asociadas en la propiedad 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.

PropiedadesProperties Valor inicialInitial value
ConnectionString connectionString
ConnectionTimeout 1515
Database cadena vacía ("")empty string ("")
DataSource cadena vacía ("")empty string ("")

Solo puede cambiar el valor de estas propiedades mediante la propiedad ConnectionString.You can change the value for these properties only by using the ConnectionString property. La clase SqlConnection proporciona funcionalidad para crear y administrar el contenido de las cadenas de conexión.The SqlConnection class provides functionality for creating and managing the contents of connection strings.

Consulte también:

SqlConnection(String, SqlCredential)

Inicializa una nueva instancia de la clase SqlConnection a la que se proporciona una cadena de conexión que no usa Integrated Security = true y un objeto SqlCredential que contiene el identificador de usuario y la contraseña.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

Cadena de conexión que no usa ninguna de las palabras clave siguientes de cadena de conexión: Integrated Security = true, UserId o Password; o que no 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

Objeto SqlCredential.A SqlCredential object. Si credential es null, SqlConnection(String, SqlCredential) es funcionalmente equivalente a SqlConnection(String).If credential is null, SqlConnection(String, SqlCredential) is functionally equivalent to SqlConnection(String).

Consulte también:

Se aplica a