473,837 Members | 1,705 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to close sqldatareader when error occur

Hi

Please help me out, I can't find a way to close a sqldatareader when error
occur at statement cmd.ExecuteRead er(). I can't close it in catch because
it is local in try scope and I can't declare it outside try scope either
since we have to call cmd.executeRead er to create sqldatareader

public string GetLogs(int logID)

{

string notes = String.Empty;

// cannot declare like SqlDataReader dr;

try

{

SqlCommand cmd = new SqlCommand("Get Logs", oConn);

cmd.CommandType = CommandType.Sto redProcedure;

cmd.Parameters. Add("@ID",SqlDb Type.Int).Value = logID;

SqlDataReader dr = cmd.ExecuteRead er();

if (dr.Read())

{

notes = dr["Notes"].ToString();

}

dr.Close();

}

catch(SqlExcept ion ex)

{

//can't call dr.Close() because it's not global

}

return notes;

}
Nov 19 '05 #1
4 2369
You can declare this:

SqlDataReader dr = null;

you can let the framework handle that though:

using(SqlConnec tion oConn = new SqlConnection(" My Conn String"))
using(SqlComman d cmd = new SqlCommand("Get Logs", oConn))
{
cmd.CommandType = CommandType.Sto redProcedure;
cmd.Parameters. Add("@ID", SqlDbType.Int). Value = logID;
using(SqlDataRe ader dr = cmd.ExecuteRead er())
{
if(dr.Read())
notes = dr["Notes"].ToString();
}
}
"mimi" wrote:
Hi

Please help me out, I can't find a way to close a sqldatareader when error
occur at statement cmd.ExecuteRead er(). I can't close it in catch because
it is local in try scope and I can't declare it outside try scope either
since we have to call cmd.executeRead er to create sqldatareader

public string GetLogs(int logID)

{

string notes = String.Empty;

// cannot declare like SqlDataReader dr;

try

{

SqlCommand cmd = new SqlCommand("Get Logs", oConn);

cmd.CommandType = CommandType.Sto redProcedure;

cmd.Parameters. Add("@ID",SqlDb Type.Int).Value = logID;

SqlDataReader dr = cmd.ExecuteRead er();

if (dr.Read())

{

notes = dr["Notes"].ToString();

}

dr.Close();

}

catch(SqlExcept ion ex)

{

//can't call dr.Close() because it's not global

}

return notes;

}

Nov 19 '05 #2
Yes you can declare it out side the try block:

Dim dr as datareader

Try
dr = cmd.ExecuteRead er();
Catch ex as SQlException

Finally
dr.close
End try

You should also be closing that datareader in the finally section of your
exception handler.
"mimi" <mh****@hotmail .com> wrote in message
news:%2******** *******@TK2MSFT NGP09.phx.gbl.. .
Hi

Please help me out, I can't find a way to close a sqldatareader when error
occur at statement cmd.ExecuteRead er(). I can't close it in catch because
it is local in try scope and I can't declare it outside try scope either
since we have to call cmd.executeRead er to create sqldatareader

public string GetLogs(int logID)

{

string notes = String.Empty;

// cannot declare like SqlDataReader dr;

try

{

SqlCommand cmd = new SqlCommand("Get Logs", oConn);

cmd.CommandType = CommandType.Sto redProcedure;

cmd.Parameters. Add("@ID",SqlDb Type.Int).Value = logID;

SqlDataReader dr = cmd.ExecuteRead er();

if (dr.Read())

{

notes = dr["Notes"].ToString();

}

dr.Close();

}

catch(SqlExcept ion ex)

{

//can't call dr.Close() because it's not global

}

return notes;

}

Nov 19 '05 #3
Hi mimi,

You certainly CAN declare it outside the try scope. All you are declaring is
a variable, not a SqlDataReader. The variable is like a box to put the
SqlDataReader IN. You should also set it to null, and check for null when
you attempt to close it. And you should close it in the finally block, which
ALWAYS executes. Example:

public string GetLogs(int logID)

{

string notes = String.Empty;

SqlDataReader dr = null;

try

{

SqlCommand cmd = new SqlCommand("Get Logs", oConn);

cmd.CommandType = CommandType.Sto redProcedure;

cmd.Parameters. Add("@ID",SqlDb Type.Int).Value = logID;

dr = cmd.ExecuteRead er();

if (dr.Read())

{

notes = dr["Notes"].ToString();

}

dr.Close();

}

catch(SqlExcept ion ex)

{
...
}
finally
{
if (dr != null)
dr.Close()
return notes;
}
}

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
The sun never sets on
the Kingdom of Heaven

"mimi" <mh****@hotmail .com> wrote in message
news:%2******** *******@TK2MSFT NGP09.phx.gbl.. .
Hi

Please help me out, I can't find a way to close a sqldatareader when error
occur at statement cmd.ExecuteRead er(). I can't close it in catch because
it is local in try scope and I can't declare it outside try scope either
since we have to call cmd.executeRead er to create sqldatareader

public string GetLogs(int logID)

{

string notes = String.Empty;

// cannot declare like SqlDataReader dr;

try

{

SqlCommand cmd = new SqlCommand("Get Logs", oConn);

cmd.CommandType = CommandType.Sto redProcedure;

cmd.Parameters. Add("@ID",SqlDb Type.Int).Value = logID;

SqlDataReader dr = cmd.ExecuteRead er();

if (dr.Read())

{

notes = dr["Notes"].ToString();

}

dr.Close();

}

catch(SqlExcept ion ex)

{

//can't call dr.Close() because it's not global

}

return notes;

}

Nov 19 '05 #4
thanks. It works for me with setting SqlDataReader to null

public string GetLogs(int logID)
{
string notes = String.Empty;
SqlDataReader dr = null;

try
{
SqlCommand cmd = new SqlCommand("Get Logs", oConn);
cmd.CommandType = CommandType.Sto redProcedure;
cmd.Parameters. Add("@ID",SqlDb Type.Int).Value = logID;
dr = cmd.ExecuteRead er();

if (dr.Read())
{
notes = dr["Notes"].ToString();
}
}
catch(SqlExcept ion ex)
{
...
}
finally
{
if (dr != null)
dr.Close()
}
return notes;

}

"Kevin Spencer" <ke***@DIESPAMM ERSDIEtakempis. com> wrote in message
news:OH******** ******@TK2MSFTN GP15.phx.gbl...
Hi mimi,

You certainly CAN declare it outside the try scope. All you are declaring is a variable, not a SqlDataReader. The variable is like a box to put the
SqlDataReader IN. You should also set it to null, and check for null when
you attempt to close it. And you should close it in the finally block, which ALWAYS executes. Example:

public string GetLogs(int logID)

{

string notes = String.Empty;

SqlDataReader dr = null;

try

{

SqlCommand cmd = new SqlCommand("Get Logs", oConn);

cmd.CommandType = CommandType.Sto redProcedure;

cmd.Parameters. Add("@ID",SqlDb Type.Int).Value = logID;

dr = cmd.ExecuteRead er();

if (dr.Read())

{

notes = dr["Notes"].ToString();

}

dr.Close();

}

catch(SqlExcept ion ex)

{
...
}
finally
{
if (dr != null)
dr.Close()
return notes;
}
}

--
HTH,

Kevin Spencer
Microsoft MVP
.Net Developer
The sun never sets on
the Kingdom of Heaven

"mimi" <mh****@hotmail .com> wrote in message
news:%2******** *******@TK2MSFT NGP09.phx.gbl.. .
Hi

Please help me out, I can't find a way to close a sqldatareader when error occur at statement cmd.ExecuteRead er(). I can't close it in catch because it is local in try scope and I can't declare it outside try scope either
since we have to call cmd.executeRead er to create sqldatareader

public string GetLogs(int logID)

{

string notes = String.Empty;

// cannot declare like SqlDataReader dr;

try

{

SqlCommand cmd = new SqlCommand("Get Logs", oConn);

cmd.CommandType = CommandType.Sto redProcedure;

cmd.Parameters. Add("@ID",SqlDb Type.Int).Value = logID;

SqlDataReader dr = cmd.ExecuteRead er();

if (dr.Read())

{

notes = dr["Notes"].ToString();

}

dr.Close();

}

catch(SqlExcept ion ex)

{

//can't call dr.Close() because it's not global

}

return notes;

}


Nov 19 '05 #5

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

Similar topics

22
31309
by: Bryan | last post by:
i'm curious to know how others handle the closing of files. i seem to always end up with this pattern even though i rarely see others do it. f1 = file('file1') try: # process f1 finally: f1.close() which explicitly closes f1
3
373
by: sam | last post by:
Hello group, I have a function which is used to initiate sqlDataReader object. I was trying to invoke the close method on the DataReader object but cant really do that as the function returns a datareader and cannot access the datareader once the connection is closed. Here is what I do: public function getDataReader() as datareader
1
4944
by: huzz | last post by:
I have a method that gets sqldatareader as shown below.. my question is how do i close the sqlconnection (objConn) object within this method? If i put the objconn.Close(); after the return then i get "Unreachable code detected" and if i close it before the return i get "Invalid attempt to FieldCount when reader is closed." When i refresh the page .. lot of sqlconnection is created.. and then i get this error message : Timeout expired....
3
4854
by: branton ellerbee | last post by:
I am looping through a datareader and building a table. However, no matter what the resultset, the datareader skips the first row of data, then builds the rest of the resultset. I have seen this occur in a lot of different places since using .Net. HAs anyone else found this problem before?
3
1540
by: Woody Splawn | last post by:
I have some code which I will show below that opens a SQLDataReader, gets some information and then closes. My question is, what is the proper way to close? Do I close the reader first and then attempt to close SQLCommand and the SQLConnection? Do I close the SQLCommand and the SQLConnection and then the SQLDataReader? Do I need to check the conneciton state for each? What is the proper way? mySqlConnection = New...
5
7899
by: jjmraz | last post by:
Hi, I have a situation where in a dll a SqlDataReader is created on a function call but is never closed. The datareader gets passed back to the asp.net page calling it. How should I close the SqldataReader in the function where it is being created properly? If I close the SqlDataReader in the function my datareader returns nothing of course. So how do I code it properly to pass back a datareader and close it in the function?
17
2388
by: Alan Silver | last post by:
Hello, I have a generic method in a utility class that grabs an sqldatareader and returns it. Due to the fact that (AFAIK), you can't close the database connection before you've read the data, this method doesn't close it, it just returns the datareader. The calling code uses the datareader and then just lets it drop out of scope, to be picked up by the garbage collector. Is this a problem? A friend of mine suggested to me that not...
4
2532
by: Learner | last post by:
Hello, This my a method to call a stored proce and uses a DataReader to read the data in the below method I am trying to assign a null value to my datareader variable Dim datareader As SqlDataReader datareader = null but it doesn't accept.
5
2553
by: jobs | last post by:
re: try catch finally to close and dispose, but still want Application_error to fire 1. If catch an exception to to dispose and close of a ado connect, how can I allow the exception to still trigger my application_error event? 2. And/Or, Is there any way to close and dispose of connections left behind by methods that might have failed without closing connections in the application_error event?
0
9685
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10886
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10634
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7817
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7007
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5674
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5853
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4479
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3126
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.