SqlCommand.Prepare Método

Definición

Crea una versión preparada del comando en una instancia de SQL Server.

public:
 override void Prepare();
public:
 virtual void Prepare();
public override void Prepare ();
public void Prepare ();
override this.Prepare : unit -> unit
abstract member Prepare : unit -> unit
override this.Prepare : unit -> unit
Public Overrides Sub Prepare ()
Public Sub Prepare ()

Implementaciones

Ejemplos

En el siguiente ejemplo se muestra el uso del método Prepare.

private static void SqlCommandPrepareEx(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        SqlCommand command = new SqlCommand(null, connection);

        // Create and prepare an SQL statement.
        command.CommandText =
            "INSERT INTO Region (RegionID, RegionDescription) " +
            "VALUES (@id, @desc)";
        SqlParameter idParam = new SqlParameter("@id", SqlDbType.Int, 0);
        SqlParameter descParam =
            new SqlParameter("@desc", SqlDbType.Text, 100);
        idParam.Value = 20;
        descParam.Value = "First Region";
        command.Parameters.Add(idParam);
        command.Parameters.Add(descParam);

        // Call Prepare after setting the Commandtext and Parameters.
        command.Prepare();
        command.ExecuteNonQuery();

        // Change parameter values and call ExecuteNonQuery.
        command.Parameters[0].Value = 21;
        command.Parameters[1].Value = "Second Region";
        command.ExecuteNonQuery();
    }
}
Private Sub SqlCommandPrepareEx(ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        connection.Open()
        Dim command As New SqlCommand("", connection)

        ' Create and prepare an SQL statement.
        command.CommandText = _
           "INSERT INTO Region (RegionID, RegionDescription) " & _
           "VALUES (@id, @desc)"
        Dim idParam As SqlParameter = _
            New SqlParameter("@id", SqlDbType.Int, 0)
        Dim descParam As SqlParameter = _
            New SqlParameter("@desc", SqlDbType.Text, 100)
        idParam.Value = 20
        descParam.Value = "First Region"
        command.Parameters.Add(idParam)
        command.Parameters.Add(descParam)

        ' Call Prepare after setting the Commandtext and Parameters.
        command.Prepare()
        command.ExecuteNonQuery()

        ' Change parameter values and call ExecuteNonQuery.
        command.Parameters(0).Value = 21
        command.Parameters(1).Value = "Second Region"
        command.ExecuteNonQuery()
    End Using
End Sub

Comentarios

Si CommandType se establece StoredProcedureen , la llamada a Prepare debe realizarse correctamente, aunque puede provocar una operación sin operación.

Antes de llamar a Prepare, especifique el tipo de datos de cada parámetro de la instrucción que se va a preparar. Para cada parámetro que tenga un tipo de datos de longitud variable, debe establecer la Size propiedad en el tamaño máximo necesario. Prepare devuelve un error si no se cumplen estas condiciones.

Nota

Si se cambia el contexto de la base de datos ejecutando la instrucción Transact-SQL USE <database> o llamando al ChangeDatabase método , Prepare se debe llamar a una segunda vez.

Si llama a un Execute método después de llamar a Prepare, cualquier valor de parámetro mayor que el valor especificado por la Size propiedad se trunca automáticamente al tamaño especificado original del parámetro y no se devuelve ningún error de truncamiento.

Los parámetros de salida (ya sean preparados o no) deben tener un tipo de datos especificado por el usuario. Si especifica un tipo de datos de longitud variable, también debe especificar el máximo Size.

Antes de Visual Studio 2010, Prepare se produjo una excepción. A partir de Visual Studio 2010, este método no produce una excepción.

Se aplica a

Consulte también