CreateCommand
IDbCommand cmd
= Connection.CreateCommand();
Returns a strongly typed provider-specific
IDbCommand
that can execute a SQL statement. This
method is primarily useful when writing generic database access code
that can work with more than one provider. By generating an
IDbCommand
object with CreateCommand( )
, you don’t need to create a
provider-specific Command
object instance.
The following code uses the CreateCommand( )
method and is completely provider-agnostic (aside from the first two
lines, which create the provider-specific
Connection
object):
string connectionString = "Data Source=localhost;" + "Initial Catalog=Northwind;Integrated Security=SSPI"; IDbConnection con = new SqlConnection(connectionString); IDbCommand cmd = con.CreateCommand(); cmd.CommandText = "SELECT * FROM Categories"; try { con.Open(); IDataReader r = cmd.ExecuteReader(); // (Read the results here.) r.Close(); } finally { con.Close(); }