C# ADO.NET OleDbCommand - ExecuteReader

The ExecuteReader() method within the OleDbCommand Object is utilized to send SQL statements to the associated C# Connection Object and populate an OleDbDataReader Object based on the executed SQL statement.

ExecuteReader() method

When the ExecuteReader() method is invoked on an OleDbCommand Object, it instantiates an instance of the OleDbDataReader Object. The OleDbDataReader Object is specifically designed for stream-based, forward-only, and read-only retrieval of query results from the Data Source. It serves as a valuable tool for efficiently retrieving data from the Data Source without the ability to modify or update the data.

OleDbDataReader reader = cmd.ExecuteReader();

It is important to note that the OleDbDataReader Object cannot be directly created from the code. Instead, it can only be generated by calling the ExecuteReader() method on a Command Object within the C# application. This ensures that the OleDbDataReader Object is associated with the appropriate SQL statement execution and maintains the necessary connection to the Data Source.

Full Source C#
using System; using System.Windows.Forms; using System.Data.OleDb; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string connetionString = null; OleDbConnection cnn ; OleDbCommand cmd ; string sql = null; OleDbDataReader reader ; connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"; sql = "Your SQL Statement Here like Select * from product"; cnn = new OleDbConnection(connetionString); try { cnn.Open(); cmd = new OleDbCommand(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 ! "); } } } }

Conclusion

The ExecuteReader() method in the OleDbCommand Object facilitates the execution of SQL statements, generating an OleDbDataReader Object that enables stream-based, forward-only, read-only retrieval of query results. The OleDbDataReader Object can only be created by invoking the ExecuteReader() method on a Command Object, ensuring proper association with the executed SQL statement and the underlying Data Source.