Thursday 17 September 2015

What is SqlDataReader

What is SqlDataReader
DataReader Provides a way of reading a forward-only stream of rows from SQL Server database. This class cannot be inherited.

OR

DataReader is used to read the data from database and it is a read and forward only connection oriented architecture during fetch the data from database.

DataReader is used to iterate through resultset that came from server and it will read one record at a time because of that memory consumption will be less and it will fetch the data very fast when compared with dataset

namespace:-

using System.Data.SqlClient;

SqlDataReader has a Read() method through which we can read data from database. Such as

SqlDataReader reader = cmd.ExecuteReader();

The father of SqlDataReader is DbDataReader. Some times some programmer saysSqlDataReader is MarshalByRefObject.

For example we can see following code in which SqlDataReader is used for read data form database.

  

//Search code here
        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtRollno.Text == "")
                {
                    lblMessage.ForeColor = Color.Red;
                    lblMessage.Text = "Roll number field should not be blank.";
                    return;
                }
                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    SqlCommand cmd = new SqlCommand("Select * from tblDemo where Rollno=@Rollno", con);
                    cmd.Parameters.AddWithValue("@Rollno", Convert.ToInt32(txtRollno.Text));
                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }

                    SqlDataReader reader = cmd.ExecuteReader(); //SqlDataReader is used here
                    if (reader.HasRows)
                    {
                          reader.Read();        //Read() method is called here
                        
                        txtName.Text = reader["Name"].ToString();
                        txtBranch.Text = reader["Branch"].ToString();
                       
                    }
                    else
                    {
                        lblMessage.ForeColor = Color.Red;
                        lblMessage.Text = "Record has not been founded.";
                    }
                }
            }
            catch
            {
                lblMessage.ForeColor = Color.Red;
                lblMessage.Text = "Input data is not in correct format.";
            }
            
        }

No comments:

Post a Comment