What is the purpose of Datareader in ADO.NET?

Datareader is used to read data from a database. Before reading the data, you should create a connection and write your query to fetch data from the database using command object.



Once these two steps are done, you can use datareader to read the resultant rows of the query defined in the command object. Here is a simple example:

class sampleClass {
public static void Main() {
string sampleConnString = “Persist Security Info = False; Initial Catalog =
sampleDB;Data Source= sampleDataServer; User ID = scott; password=tiger”;
SqlConnection sampleConn = new SQLConnection(sampleConnString);
string sampleQuery = “select rollNo, studName from student”;
SqlCommand sampleCmd = new SqlCommand(sampleQuery, sampleConn);
sampleConn.Open();
SqlDataReader sampleReader = sampleCmd.ExecuteReader();
if(sampleReader.HasRows) {
while (sampleReader.Read()) {
Console.WriteLine(“RollNo: {0}, Name:{1}”,
sampleReader.GetString(0), sampleReader.GetString(1));
}
}
sampleReader.Close();
sampleConn.Close();

| What is Private Access Modifier in C#? | What is Protected Access Modifier in C#? | What is Protected Internal Access Modifier in C#? | What is Public Access Modifier in C#? | What is the difference between virtual and abstract keywords in .NET? | What is the importance of Microsoft Application Blocks in .NET Architecture? | What is the need for Factory Method in C# | What is the purpose of ArrayList in .NET? | What is the purpose of Datareader in ADO.NET? | What is the purpose of Dataset in ADO.NET? | What is the purpose of finally block in C#? | What is the purpose of interlocked class in .NET? | What is the purpose of main() function in C# | What is the purpose of ManualResetEvent in .NET? | What is the purpose of sealed method in C#? | What is the purpose of Thread.Join() method in .NET? | What is the purpose of Thread.Sleep() method in .NET? | What is the purpose of throw keyword in C#? | What is the usage of ENUM in .NET? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.