473,396 Members | 1,832 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Passing a DataReader between methods and getting RETURN_VALUE

Hi all,

I have the following problem:

I have a private method that returns a SqlDataReader. For this to work I
have not to close the DB connection in the above method. I do this only to
have the possibility to iterate through the entire rows set in a while loop,
located in the calling method.

I have included a few lines of code to get the number of rows fetched from
the DB. I do this with SqlParameter("RETURN_VALUE", SqlDbType.Int) [ I am
using a stored procedure that return @@rowcount].

I have found out that I am getting the appropriate value for the stored
procedure parameter ("RETURN_VALUE") ONLY when I have explicitly close the
DB connection. Unfortunately when the control is returned to the calling
method the usual error message

Invalid attempt to Read when reader is closed

is being received as the connection is closed and there's no such DataReader
already.

Does anyone know a workaround for this?

Thanks,

Martin

------------------------

private SqlDataReader GetReader(string parameter, string date)

{

DateTime MyDateTime;

.....//. date parsing
SqlConnection myConn = new SqlConnection(ConnectionString());
SqlCommand myCmd = new SqlCommand();

SqlDataReader myReader=null;

myCmd.CommandType = CommandType.StoredProcedure;
myCmd.Connection = myConn;
myCmd.CommandText = "GetData";
myCmd.CommandTimeout = 250;

SqlParameter Param1 = new SqlParameter();
Param1 = myCmd.Parameters.Add("@parameter", SqlDbType.VarChar, 12);
Param1.Direction = ParameterDirection.Input;
Param1.Value = parameter;

SqlParameter Param2 = new SqlParameter();
Param2 = myCmd.Parameters.Add("@date", SqlDbType.VarChar, 20);
Param2.Direction = ParameterDirection.Input;
Param2.Value = MyDateTime.Date.ToShortDateString();
SqlParameter outValue = new SqlParameter();
outValue = myCmd.Parameters.Add("RETURN_VALUE", SqlDbType.Int);
outValue.Direction = ParameterDirection.ReturnValue;

myConn.Open();
myReader = myCmd.ExecuteReader();

// this works only is myConn.Close() is executed but then

// we cannot return a READER to the calling method???

intRowsReturned =
Convert.ToInt32(myCmd.Parameters["RETURN_VALUE"].Value);
return myReader;
}

// the calling method

private void btnSQLGet_Click(object sender, System.EventArgs e)

{

/// ... .

// get the data in a reader

SqlDataReader myReader = GetReader(cboParameter.Text, txtDate.Text);
if (myReader==null)
return;
///.....

}

Nov 18 '05 #1
2 8040
You can't read output parameters in a DataReader until the DataReader is
closed. Close the DataReader, and leave the Connection opened to read the
value.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.

"Martin Raychev" <ma*******@hotmail.com> wrote in message
news:#R**************@TK2MSFTNGP09.phx.gbl...
Hi all,

I have the following problem:

I have a private method that returns a SqlDataReader. For this to work I
have not to close the DB connection in the above method. I do this only to
have the possibility to iterate through the entire rows set in a while loop, located in the calling method.

I have included a few lines of code to get the number of rows fetched from
the DB. I do this with SqlParameter("RETURN_VALUE", SqlDbType.Int) [ I am
using a stored procedure that return @@rowcount].

I have found out that I am getting the appropriate value for the stored
procedure parameter ("RETURN_VALUE") ONLY when I have explicitly close the
DB connection. Unfortunately when the control is returned to the calling
method the usual error message

Invalid attempt to Read when reader is closed

is being received as the connection is closed and there's no such DataReader already.

Does anyone know a workaround for this?

Thanks,

Martin

------------------------

private SqlDataReader GetReader(string parameter, string date)

{

DateTime MyDateTime;

.....//. date parsing
SqlConnection myConn = new SqlConnection(ConnectionString());
SqlCommand myCmd = new SqlCommand();

SqlDataReader myReader=null;

myCmd.CommandType = CommandType.StoredProcedure;
myCmd.Connection = myConn;
myCmd.CommandText = "GetData";
myCmd.CommandTimeout = 250;

SqlParameter Param1 = new SqlParameter();
Param1 = myCmd.Parameters.Add("@parameter", SqlDbType.VarChar, 12);
Param1.Direction = ParameterDirection.Input;
Param1.Value = parameter;

SqlParameter Param2 = new SqlParameter();
Param2 = myCmd.Parameters.Add("@date", SqlDbType.VarChar, 20);
Param2.Direction = ParameterDirection.Input;
Param2.Value = MyDateTime.Date.ToShortDateString();
SqlParameter outValue = new SqlParameter();
outValue = myCmd.Parameters.Add("RETURN_VALUE", SqlDbType.Int);
outValue.Direction = ParameterDirection.ReturnValue;

myConn.Open();
myReader = myCmd.ExecuteReader();

// this works only is myConn.Close() is executed but then

// we cannot return a READER to the calling method???

intRowsReturned =
Convert.ToInt32(myCmd.Parameters["RETURN_VALUE"].Value);
return myReader;
}

// the calling method

private void btnSQLGet_Click(object sender, System.EventArgs e)

{

/// ... .

// get the data in a reader

SqlDataReader myReader = GetReader(cboParameter.Text, txtDate.Text);
if (myReader==null)
return;
///.....

}

Nov 18 '05 #2
1) the return value and parameters values of a stored proc are returned
after all result sets in the proc are returned.
2) a datareader is a forward only cursor, so to get to the return value, you
need to read thru all rows, and result sets
3) a close will read thru all rows and result sets for you, but is not
necessary, the following code will also work:

// process all result sets to get to parameters and reutn value

do
{
while (dr.Read())
;
} while (dr.NextResult())

// now you can access output parameters and the return value

returning a row count makes little sesnse, as you could add up the row
count yourself, as you have to read them all to get to the count return
value.

-- bruce (sqlwork.com)
"Martin Raychev" <ma*******@hotmail.com> wrote in message
news:#R**************@TK2MSFTNGP09.phx.gbl...
Hi all,

I have the following problem:

I have a private method that returns a SqlDataReader. For this to work I
have not to close the DB connection in the above method. I do this only to
have the possibility to iterate through the entire rows set in a while loop, located in the calling method.

I have included a few lines of code to get the number of rows fetched from
the DB. I do this with SqlParameter("RETURN_VALUE", SqlDbType.Int) [ I am
using a stored procedure that return @@rowcount].

I have found out that I am getting the appropriate value for the stored
procedure parameter ("RETURN_VALUE") ONLY when I have explicitly close the
DB connection. Unfortunately when the control is returned to the calling
method the usual error message

Invalid attempt to Read when reader is closed

is being received as the connection is closed and there's no such DataReader already.

Does anyone know a workaround for this?

Thanks,

Martin

------------------------

private SqlDataReader GetReader(string parameter, string date)

{

DateTime MyDateTime;

.....//. date parsing
SqlConnection myConn = new SqlConnection(ConnectionString());
SqlCommand myCmd = new SqlCommand();

SqlDataReader myReader=null;

myCmd.CommandType = CommandType.StoredProcedure;
myCmd.Connection = myConn;
myCmd.CommandText = "GetData";
myCmd.CommandTimeout = 250;

SqlParameter Param1 = new SqlParameter();
Param1 = myCmd.Parameters.Add("@parameter", SqlDbType.VarChar, 12);
Param1.Direction = ParameterDirection.Input;
Param1.Value = parameter;

SqlParameter Param2 = new SqlParameter();
Param2 = myCmd.Parameters.Add("@date", SqlDbType.VarChar, 20);
Param2.Direction = ParameterDirection.Input;
Param2.Value = MyDateTime.Date.ToShortDateString();
SqlParameter outValue = new SqlParameter();
outValue = myCmd.Parameters.Add("RETURN_VALUE", SqlDbType.Int);
outValue.Direction = ParameterDirection.ReturnValue;

myConn.Open();
myReader = myCmd.ExecuteReader();

// this works only is myConn.Close() is executed but then

// we cannot return a READER to the calling method???

intRowsReturned =
Convert.ToInt32(myCmd.Parameters["RETURN_VALUE"].Value);
return myReader;
}

// the calling method

private void btnSQLGet_Click(object sender, System.EventArgs e)

{

/// ... .

// get the data in a reader

SqlDataReader myReader = GetReader(cboParameter.Text, txtDate.Text);
if (myReader==null)
return;
///.....

}

Nov 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

125
by: Raymond Hettinger | last post by:
I would like to get everyone's thoughts on two new dictionary methods: def count(self, value, qty=1): try: self += qty except KeyError: self = qty def appendlist(self, key, *values): try:
6
by: Yasutaka Ito | last post by:
Hi, My friend had a little confusion about the working of DataReader after reading an article from MSDN. Following is a message from him... <!-- Message starts --> I was going thru DataReader...
11
by: Steven D'Aprano | last post by:
Suppose I create a class with some methods: py> class C: .... def spam(self, x): .... print "spam " * x .... def ham(self, x): .... print "ham * %s" % x .......
11
by: Johnny | last post by:
I'm a rookie at C# and OO so please don't laugh! I have a form (fclsTaxCalculator) that contains a text box (tboxZipCode) containing a zip code. The user can enter a zip code in the text box and...
5
by: blue | last post by:
We often get connection pooling errors saying that there are no available connections in the pool. I think the problem is that we are passing around open readers all over the place. I am...
6
by: Max | last post by:
Anyone know why I'm always getting 0 returned? My stored procedure returns -1. Dim iErrorCode As Int32 iErrorCode = Convert.ToInt32(SqlHelper.ExecuteScalar(AppVars.strConn, _ "gpUpdateMember",...
3
by: Miguel | last post by:
Hi, I'm new to .NET and am using VB .NET as I am from a VB background. I am having difficulty understanding the way .NET handles, passes and uses objects. I have had a look at the Micrsoft Data...
11
by: ^MisterJingo^ | last post by:
Hi all, I have a form with 4 dropdownlist controls which I populate with data from DB tables. I have a class with a method which constructs a dataset, putting each DB table into a dataset table....
9
by: Greger | last post by:
Hi, I am building an architecture that passes my custom objects to and from webservices. (Our internal architecture requires me to use webservices to any suggestion to use other remoting...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.