C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: The SqlCommand type has a public parameterized constructor and it can be used with one or more arguments.
And: The first parameter specifies the SQL statement. The second parameter is the SqlConnection. The third parameter is the SqlTransaction.
Important: This program interfaces with the SQL Server engine. It uses some project-specific external data.
SqlClientSqlDataReaderSo: It will not work for you unless you change the connection string reference and the SQL command text for your environment.
C# program that uses SqlCommand instance
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();
}
}
}
}
}
}
Output
7
Candy
Yorkshire Terrier
25
Charles
Cavalier King Charles Spaniel
57
Koko
Shar Pei
And: The second parameter is the SqlConnection object. This is set up elsewhere in the program.
Overview: You must manually specify the connection to use on the SqlCommand. This can be done with a parameter on the constructor.