C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ADO.NET SqlDataReader ClassThis class is used to read data from SQL Server database. It reads data in forward-only stream of rows from a SQL Server database. it is sealed class so that cannot be inherited. It inherits DbDataReader class and implements IDisposable interface. SqlDataReader Signature
public class SqlDataReader : System.Data.Common.DbDataReader, IDisposable SqlDataReader Properties
Methods
To create a SqlDataReader instance, we must call the ExecuteReader method of the SqlCommand object. Example
In the following program, we are using SqlDataReader to get data from the SQL Server. A C# code is given below. // Program.cs
using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().GetData();
}
public void GetData()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=student; integrated security=SSPI");
// writing sql query
SqlCommand cm = new SqlCommand("select * from student", con);
// Opening Connection
con.Open();
// Executing the SQL query
SqlDataReader sdr = cm.ExecuteReader();
while (sdr.Read())
{
Console.WriteLine(sdr["name"]+" "+ sdr["email"]);
}
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong." + e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}
Output: Execute this program by combination of Ctrl+F5 and it will produce the following output.
Next TopicADO.NET DataSet
|