C# ADO.NET SqlDataReader
The SqlDataReader Object in C# provides connection-oriented data access to SQL Server data sources from C# applications.
ExecuteReader() method
To retrieve data using the SqlDataReader, you typically utilize the ExecuteReader() method in the SqlCommand Object. This method sends the SQL statements or Stored Procedures to the associated SqlConnection Object and populates a SqlDataReader Object based on the executed SQL statement.
When the ExecuteReader method is executed on the SqlCommand Object, it instantiates a SqlClient.SqlDataReader Object. This SqlDataReader Object serves as a cursor that allows you to efficiently read and access the retrieved data.
Before reading from the SqlDataReader, it's important to ensure that the SqlDataReader is open and positioned prior to the first record. You can accomplish this by invoking the Read() method, which advances the SqlDataReader to the next row and returns a boolean value indicating whether there are more rows available.
Read() method
The Read() method of the DataReader is utilized to read the rows sequentially from the SqlDataReader. It always moves the cursor forward to the next valid row, if any rows exist.
By invoking the Read() method iteratively, you can retrieve the data from each row and access the values of individual columns using the appropriate getter methods (e.g., GetString(), GetInt32(), etc.) based on the data type.
Full Source C#Conclusion
The SqlDataReader Object in C# facilitates connection-oriented data access to SQL Server data sources. It is instantiated using the ExecuteReader() method in the SqlCommand Object and provides methods like Read() to sequentially retrieve and access data rows. Ensuring the SqlDataReader is open and positioned correctly before reading is crucial, and it is important to manage the connection and close the SqlDataReader and SqlConnection when finished.
- C# ADO.NET Command
- C# ADO.NET SqlCommand - ExecuteNonQuery
- C# ADO.NET OleDbCommand - ExecuteNonQuery
- C# ADO.NET SqlCommand - ExecuteScalar
- C# ADO.NET OleDbCommand - ExecuteScalar
- C# ADO.NET SqlCommand - ExecuteReader
- C# ADO.NET OleDbCommand - ExecuteReader
- C# ADO.NET DataReader
- C# ADO.NET OleDbDataReader
- C# Multiple Result Sets
- C# Table Schema from SqlDataReader
- C# Table Schema from OleDbDataReader
- C# ADO.NET DataAdapter
- C# ADO.NET SqlDataAdapter
- C# ADO.NET OleDbDataAdapter
- C# ExecuteReader and ExecuteNonQuery
- System.Data.SqlClient.SqlException: Login failed for user