posts - 31, comments - 85, trackbacks - 0

My Links

News

Archives

Post Categories

Return SqlDataReader from a method

.NET's SqlDataReader class is based on an active connection to the database. This means that while the SqlDataReader is in use, the SqlConnection that is serving the SqlDataReader is open and cannot be used anywhere else.

That is why, returning an SqlDataReader from a method is not stright forward like returning a DataTable or a DataSet. To read more about SqlDataReader, please see SqlDataReader class.

Though it is not straight forward, it is very simple. Here's a piece of code that would let you return a SqlDataReader from a method:

public SqlDataReader GetData(string item1, string item2)
{
    SqlDataReader reader = null;
    SqlConnection connection = new SqlConnection(ConnectionString);
    try
    {
        SqlCommand command = new SqlCommand();
        command.CommandType = CommandType.StoredProcedure;
       command.CommandText = "YOUR_SPROC_NAME";
       command.Parameters.Add("@Item1", SqlDbType.VarChar, 255).Value = item1;
       command.Parameters.Add("@Item2", SqlDbType.VarChar, 255).Value = item2;
        command.Connection = connection;
        connection.Open();
        reader = command.ExecuteReader(CommandBehavior.CloseConnection);
    }
    catch (Exception ex)
    {
        connection.Close();
       Response.Write(ex.Message);
    }
    return reader;

}

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Print | posted on Tuesday, May 26, 2009 1:58 AM | Filed Under [ C# ASP.NET ]

Feedback

Gravatar

# re: Return SqlDataReader from a method

hi, i tried it and did not get any return value , view below:

MySqlDataReader dr = null;

using (MySqlConnection conn = new MySqlConnection(Utils.GetConn()))
{
conn.Open();

string sql = "proc_generaloptions_Countries_Get";

try
{
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.CommandType = CommandType.StoredProcedure;

dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

}
catch (Exception ex)
{
throw new Exception(ex.Message);
}

}
HttpContext.Current.Response.Write(dr.HasRows);
return dr;
10/19/2011 5:48 AM | Michael Adom
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: