SqlDataReader provides a means of reading a forward-only stream of data records from a SQL Server data source. For more interactive operations such as scrolling, filtering, navigating, and remoting, use the DataSet.
The example creates a SqlConnection to the Northwind database. The SqlCommand selecting items from the employee table is then executed using the SqlCommand ExecuteReader method. The results of this command are passed to the SqlDataReader.
SqlDataReader myDataReader = null;
SqlConnection mySqlConnection = new SqlConnection("server=(local)\SQLExpress;Integrated Security=SSPI;database=northwind");
SqlCommand mySqlCommand = new SqlCommand("SELECT EmployeeID, LastName, FirstName, Title, ReportsTo FROM Employees", mySqlConnection);
...
mySqlConnection.Open();
myDataReader = mySqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
The example reads through the data using the SqlDataReader Read method and writing the data elements out to the console.
while (myDataReader.Read())
{
Console.Write(myDataReader.GetInt32(0) + "\t");
Console.Write(myDataReader.GetString(2) + " " + myDataReader.GetString(1) + "\t");
Console.Write(myDataReader.GetString(3) + "\t");
if (myDataReader.IsDBNull(4))
Console.Write("N/A\n");
else
Console.Write(myDataReader.GetInt32(4) + "\n");
}
Finally, the example closes the SqlDataReader, then the SqlConnection.
// Always call Close when done reading.
myDataReader.Close();
// Close the connection when done with it.
mySqlConnection.Close();
Or You can do it by alternate way click
[
Here]