Wednesday, 30 March 2011

DataReader Interview Questions

Can dataReader hold data from multiple tables?

Yes, DataReader can hold data from multiple tables.

 SqlConnection con = new SqlConnection("server=sugandha;initial catalog = dotnet;uid=sa;pwd=sugandha");
        string query = "select * from Employee; select * from Employee1";
        SqlCommand cmd = new SqlCommand(query, con);

       SqlDataReader dr = cmd.ExecuteReader();

        if (dr.HasRows)


            GridView1.DataSource = dr;


            if (dr.NextResult())

                GridView2.DataSource = dr;





How can we retrieve two tables of data at a time by using DataReader?

If we pass two queries in the commandText then we get data from two tables.
It return 2 tables in DataReader.

like :
string str="Select * from a;select * from b";

What is difference between dataset and datareader ?

Following are some major differences between dataset and datareader :

1. DataReader provides forward-only and read-only access to data , while the DataSet object can hold more than one table   from the same data source as well as the relationships between them.
2. Dataset is a disconnected architecture while datareader is connected architecture.
3. Dataset can persists contents while datareader can not persist contents , they are forward only.

I want to force the DataReader to return only schema of the datastore rather than data ?

objDataReader = objCommand.ExecuteReader(CommandBehavior.SchemaOnly)

How can we force the connection object to close after my DataReader is closed ?

ExecuteReader takes a parameter called as CommandBehavior where in we can specify saying close connection automatically after the DataReader is close.
objDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)

No comments:

Post a Comment