The ExecuteReader method returns a DbDataReader instance. (DbDataReader is covered in more detail in the next section.) The DbDataReader object is a forward-only, readonly,server-side cursor. DbDataReader objects can be created only by executing one of the ExecuteReader methods on the DbCommand object. The following example uses the ExecuteReader method to create a DbDataReader object with the selection results and then continuously loops through the results until the end of data has been reached (when the Read method returns false).
C# Code
var nw = ConfigurationManager.ConnectionStrings["nw"];
var connection = new SqlConnection();
connection.ConnectionString = nw.ConnectionString;
var cmd = connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT ProductID, UnitPrice FROM Products";
connection.Open();
DbDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
MessageBox.Show(rdr["ProductID"] + ": " + rdr["UnitPrice"]);
}
connection.Close();
C# Code
var nw = ConfigurationManager.ConnectionStrings["nw"];
var connection = new SqlConnection();
connection.ConnectionString = nw.ConnectionString;
var cmd = connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT ProductID, UnitPrice FROM Products";
connection.Open();
DbDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
MessageBox.Show(rdr["ProductID"] + ": " + rdr["UnitPrice"]);
}
connection.Close();
No comments:
Post a Comment