473,748 Members | 2,574 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 2364
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
31287
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
4939
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
4812
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
1537
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
7896
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
2380
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
2529
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
2548
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
8996
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8832
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
9562
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...
0
9386
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9333
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,...
0
8255
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4608
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...
2
2791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2217
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.