Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is There Any Difference Between SqlConnection.CreateCommand and new SqlCommand?

Tags:

c#

ado.net

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?

like image 913
Brett Bim Avatar asked Aug 19 '09 21:08

Brett Bim


People also ask

What is SqlConnection and SqlCommand in C#?

SqlConnection and SqlCommand are classes of a connected architecture and found in the System. Data. SqlClient namespace. The SqlConnection class makes a connection with the database. Further, this connection (database connection) is used by the SqlCommand to work with that database.

What does SqlCommand mean?

SQL stands for Structured Query Language. SQL commands are the instructions used to communicate with a database to perform tasks, functions, and queries with data. SQL commands can be used to search the database and to do other functions like creating tables, adding data to tables, modifying data, and dropping tables.

Why do we need SqlConnection in C#?

A SqlConnection object represents a unique session to a SQL Server data source. With a client/server database system, it is equivalent to a network connection to the server. SqlConnection is used together with SqlDataAdapter and SqlCommand to increase performance when connecting to a Microsoft SQL Server database.

What is SqlCommand C#?

SqlCommand in C# allow the user to query and send the commands to the database. SQL command is specified by the SQL connection object. Two methods are used, ExecuteReader method for results of query and ExecuteNonQuery for insert, Update, and delete commands. It is the method that is best for the different commands.


2 Answers

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.

like image 109
Andrew Hare Avatar answered Sep 28 '22 08:09

Andrew Hare


They do the same thing. The rationale behind SqlConnection.CreateCommand is to implement the factory pattern.

like image 26
mmx Avatar answered Sep 28 '22 08:09

mmx