C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: To begin, you can create a new SqlConnection and open it. We do this with the SqlConnection constructor.
ConstructorUsingThen: You can create a new SqlCommand and call its ExecuteReader method, assigning the reference it returns to an SqlDataReader.
C# program that uses SqlDataReader with SqlClient
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
//
// You need to access the project's connection string here.
//
string connectionString =
ConsoleApplication1.Properties.Settings.Default.ConnectionString;
//
// Create new SqlConnection object.
//
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//
// Create new SqlCommand object.
//
using (SqlCommand command = new SqlCommand("SELECT * FROM Dogs1", connection))
{
//
// Invoke ExecuteReader method.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int weight = reader.GetInt32(0); // Weight int
string name = reader.GetString(1); // Name string
string breed = reader.GetString(2); // Breed string
//
// Write the values read from the database to the screen.
//
Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}",
weight, name, breed);
}
}
}
}
}
Output
Weight = 57, Name = Koko, Breed = Shar Pei
Weight = 130, Name = Fido, Breed = Bullmastiff
Weight = 93, Name = Alex, Breed = Anatolian Shepherd Dog
Weight = 25, Name = Charles, Breed = Cavalier King Charles Spaniel
Weight = 7, Name = Candy, Breed = Yorkshire Terrier
Tip: You must always create a new SqlConnection before using the SqlDataReader code here.
SqlConnectionNote: SqlConnection objects use an advanced optimization called connection pooling.
So: Creating these new objects will probably not have a highly adverse affect on overall program performance.
Note: The text "SELECT * FROM Dogs1" simply selects all rows from a table called Dogs1 in the database.
Tip: This makes it possible to query the SqlDataReader for integers, strings and other types with the GetInt32 and GetString methods.
Warning: This approach is slower if you are dealing with vast amounts of data, because all of it must be stored in memory at once.
Tip: Using SqlDataReader is an easy way to print all rows from a table. It is efficient and worth knowing.