Reputation: 3318
In .Net, is there any functional difference between creating a new SqlCommand
object and attaching a SqlConnection
to it and calling CreateCommand()
on an existing SqlConnection
object?
Upvotes: 34
Views: 15205
Reputation: 3768
This may go without saying, but just to be complete, there is one difference. If you create a SqlCommand, you can pass in the CommandText as a parameter. If you let the SqlConnection CreateCommand, there is no provision for supplying the CommandText. Since you can just set the SqlCommand's CommandText property, the distinction is pretty slim, but it does exist.
SqlConnection db = new SqlConnection();
SqlCommand cmd = db.CreateCommand();
cmd.CommandText = "select @@version";
or
SqlConnection db = new SqlConnection();
SqlCommand cmd = new SqlCommand("select @@version", db);
Upvotes: 3
Reputation: 6450
Functionally they are exactly the same.
However, SqlConnection.CreateCommand()
lets you be more agnostic about what type of DB you are using. For example instead of passing a SqlConnection
instance around you could pass it around as a DbConnection
which would yield a DbCommand
.
Upvotes: 10
Reputation: 351566
No, they are the same thing.
I disassembled SqlConnection.CreateCommand
and found this:
public SqlCommand CreateCommand()
{
return new SqlCommand(null, this);
}
which proves that they really are the same thing.
Upvotes: 43
Reputation: 422132
They do the same thing. The rationale behind SqlConnection.CreateCommand
is to implement the factory pattern.
Upvotes: 13