Code Listing: DataReader
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
string queryString = "SELECT CategoryID, CategoryName FROM dbo.Categories;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader[0], reader[1]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
static private string GetConnectionString()
{
return "Data Source=(local);Initial Catalog=Northwind;" + "Integrated Security=SSPI";
} }
No comments:
Post a Comment