C# ADO.NET SqlCommand - ExecuteReader

The ExecuteReader() method within the C# SqlCommand Object plays a key role in executing SQL statements and retrieving query results from the connected Data Source. This method is responsible for sending the SQL statements to the associated Connection Object and populating a SqlDataReader Object based on the executed SQL statement.

ExecuteReader() method

When the ExecuteReader() method is invoked, it triggers the instantiation of a SqlClient.SqlDataReader Object. This SqlDataReader Object serves as a stream-based mechanism for retrieving query results from the Data Source in a forward-only manner. It provides read-only access to the retrieved data, without the capability to update or modify the underlying data.

Full Source C#
using System; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string connetionString = null; SqlConnection cnn ; SqlCommand cmd ; string sql = null; SqlDataReader reader ; connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"; sql = "Your SQL Statement Here , like Select * from product"; cnn = new SqlConnection(connetionString); try { cnn.Open(); cmd = new SqlCommand(sql, cnn); reader = cmd.ExecuteReader(); while (reader.Read()) { MessageBox.Show(reader.GetValue(0) + " - " + reader.GetValue(1) + " - " + reader.GetValue(2)); } reader.Close(); cmd.Dispose(); cnn.Close(); } catch (Exception ex) { MessageBox.Show("Can not open connection ! "); } } } }

It's important to note that the SqlDataReader Object cannot be created directly through code. Instead, it is generated by calling the ExecuteReader() method of a C# Command Object. This design ensures that the SqlDataReader Object is properly linked to the executed SQL statement and the associated Data Source, facilitating the seamless retrieval of query results.

Conclusion

Using the ExecuteReader() method and the SqlDataReader Object, developers can efficiently retrieve and process data from the Data Source in a read-only manner. This streamlined approach enhances the performance and usability of data retrieval operations within the ADO.NET framework.