System.Data Namespace IDbCommand Class
Initializes a prepared version of the command on the data source.
[ VB ]
NotOverridable Public Sub Prepare ( )
[ C# ]
public void Prepare ( );
[ C++ ]
public: __sealed void Prepare ( );
[ JScript ]
public function Prepare ( );
If the CommandType property is set to TableDirect, Prepare does nothing. If CommandType is set to StoredProcedure, the call to Prepare should succeed, although it may result in a no-op.
Before you call Prepare, specify the data type of each parameter in the statement to be prepared. For each parameter that has a variable length data type, you must set the Size property to the maximum size needed. Prepare returns an error if these conditions are not met.
If you call an Execute method after calling Prepare, any parameter value that is larger than the value specified by the Size property is automatically truncated to the original specified size of the parameter, and no truncation errors are returned.
Output parameters ( whether prepared or not ) must have a user-specified data type. If you specify a variable length data type, you must also specify the maximum Size.
The following example demonstrates the use of the Prepare method.
void SqlCommandPrepareEx ( ) {
int id = 20;
string desc = "myFirstRegion" ;
SqlConnection myConn = new SqlConnection (
"server=localhost; uid=sa; pwd=; database=northwind" );
myConn.Open ( );
SqlCommand myCmd = new SqlCommand ( null, myConn );
// set up insert myCmd ...
myCmd.CommandText = "insert into Region ( RegionID, RegionDescription )
values ( @id, @desc ) " ;
myCmd.Parameters.Add ( "@id", id );
myCmd.Parameters.Add ( "@desc", desc );
// calling Prepare after having setup commandtext and params.
myCmd.Prepare ( );
myCmd.ExecuteNonQuery ( );
// change param values and call execute. This time the prepared myCmd will be executed.
myCmd.Parameters [ 0 ].Value = 21;
myCmd.Parameters [ 1 ].Value = "mySecondRegion";
myCmd.ExecuteNonQuery ( );
}
Public Sub SqlCommandPrepare ( )
Dim id As Integer = 20
Dim desc As String = "myFirstRegion"
Dim myConn As SqlConnection = New SqlConnection ( _
"server=localhost; uid=sa; pwd=; database=northwind" )
myConn.Open ( )
Dim myCmd As New SqlCommand ( "", myConn )
' set up insert myCmd ...
myCmd.CommandText = "insert into Region ( RegionID, RegionDescription ) _
values ( @id, @desc ) "
myCmd.Parameters.Add ( "@id", id )
myCmd.Parameters.Add ( "@desc", desc )
' Calling Prepare after having setup commandtext and params.
myCmd.Prepare ( )
myCmd.ExecuteNonQuery ( )
' Change param values and call execute. This time the prepared myCmd will be executed.
myCmd.Parameters ( 0 ).Value = 21
myCmd.Parameters ( 1 ).Value = "mySecondRegion"
myCmd.ExecuteNonQuery ( )
End Sub |
|
C# |
VB |
IDbCommand Members