using System;
using System.Data.SqlClient;
namespace pc.sqldatareaderExample
{
class Program
{
static string cs =
@"Data
Source=BEAST\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
static void Main(string[] args)
{
string GetPersons = "SELECT * from
Person;";
//using
statement to ensure dispose of
using (var conn = new SqlConnection(cs))
try
{
var cmnd = new SqlCommand(GetPersons, conn);
conn.Open();
using (SqlDataReader dr = cmnd.ExecuteReader())
try
{
if (dr.HasRows)
while (dr.Read())
Console.WriteLine($"{dr[0]}) {dr[1]} {dr[2]}");
}
finally
{
dr.Close();
}
}
catch (SqlException sqlEx)
{
//display sql exception
Console.WriteLine(sqlEx.Message);
}
catch (Exception Ex)
{
//display all other exceptions
Console.WriteLine(Ex.Message);
}
finally
{
//ensure that the connection is closed everytime
conn.Close();
}
}
}
}
using System;
using System.Data.SqlClient;
namespace pc.sqldatareaderExample
{
class Program
{
static string cs =
@"Data
Source=BEAST\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
static void Main(string[] args)
{
string GetPersons = "SELECT * from
Person;SELECT * from Person;";
//using
statement to ensure dispose of
using (var conn = new SqlConnection(cs))
try
{
var cmnd = new SqlCommand(GetPersons, conn);
conn.Open();
using (SqlDataReader dr = cmnd.ExecuteReader())
try
{
do
{
if (dr.HasRows)
while (dr.Read())
Console.WriteLine($"{dr[0]}) {dr[1]} {dr[2]}");
Console.WriteLine("\n*** Next Result set***\n");
}
while (dr.NextResult());
}
finally
{
dr.Close();
}
}
catch (SqlException sqlEx)
{
//display sql exception
Console.WriteLine(sqlEx.Message);
}
catch (Exception Ex)
{
//display all
other exceptions
Console.WriteLine(Ex.Message);
}
finally
{
//ensure that the connection is closed everytime
conn.Close();
}
}
}
}