SqlCommand
This type deals with databases. It executes SQL commands on a database. It sends an SQL command to a database that is specified by an SqlConnection
object.
We then call instance methods to physically apply the command to the database. We use a SELECT TOP command text, and also ORDER BY.
This program uses the SqlCommand
data object in C#. We use SqlCommand
in the context of a complete but trivial program that reads data from a specific database on the disk.
SqlCommand
type has a public parameterized constructor and it can be used with one or more arguments.SqlConnection
. The third parameter is the SqlTransaction
.using System; using System.Data.SqlClient; class Program { static void Main() { // // The program accesses the connection string. // ... It uses it on a connection. // string conString = ConsoleApplication1.Properties.Settings.Default.ConnectionString; using (SqlConnection connection = new SqlConnection(conString)) { connection.Open(); // // SqlCommand should be created inside using. // ... It receives the SQL statement. // ... It receives the connection object. // ... The SQL text works with a specific database. // using (SqlCommand command = new SqlCommand("SELECT TOP 3 * FROM Dogs1 ORDER BY Weight", connection)) { // // Instance methods can be used on the SqlCommand. // ... These read data. // using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { Console.WriteLine(reader.GetValue(i)); } Console.WriteLine(); } } } } } }7 Candy Yorkshire Terrier 25 Charles Cavalier King Charles Spaniel 57 Koko Shar Pei
The SQL data objects are wrapped in a resource acquisition statement. This ensures that resources are properly acquired and disposed of when no longer needed.
The call to the SqlCommand
constructor uses 2 parameters. The first parameter is the actual SQL source text. This string
uses SQL and is not compiled by the C# compiler.
SqlConnection
object. This is set up elsewhere in the program.SqlCommand
. This can be done with a parameter on the constructor.We wrote a complete program that reads from a database on the local disk. The SqlCommand
has a constructor. You can specify its connection and the SQL text.