473,698 Members | 2,158 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to close sqlconnection

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 "Unreachabl e 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. The timeout period elapsed prior to obtaining a connection
from the pool. This may have occurred because all pooled connections were in
use and max pool size was reached.

Also instead of adding this bit of code
[(ConfigurationS ettings.AppSett ings["DSN"]);
SqlCommand selectCmd = new SqlCommand("sp_ DMListFiles",ob jConn)]
in every method.. how can i put it somewhere and reuse it in every methods??

Many thanks in advance.

public SqlDataReader DMListFiles(int DepID, int FolderID)
{
SqlConnection objConn = new
SqlConnection(C onfigurationSet tings.AppSettin gs["DSN"]);
SqlCommand selectCmd = new SqlCommand("sp_ DMListFiles",ob jConn);
selectCmd.Param eters.Add("@Dep ID",DepID);
selectCmd.Param eters.Add("@Fol derID",FolderID );
selectCmd.Comma ndType = CommandType.Sto redProcedure;
objConn.Open();
SqlDataReader dr = selectCmd.Execu teReader();
return dr;
}
Jul 21 '05 #1
1 4934
Hi,

you can't close it in the same method after you've returned it. It lefts
that responsibility to the caller of this method. Least you can do is to
call ExecuteReader method with CloseConnection argument that is:

SqlDataReader dr = selectCmd.Execu teReader(Comman dBehavior.Close Connection);
return dr;

which would force the connection to be closed when Datareader is closed, but
still the caller *must* call Close/Dispose for the data reader instance

However, there is a way around it, simplest being that start using data
tables, but you can check a few articles about these issues how you can
manage with data readers in a case like this.

Using Delegates With Data Readers to Control DAL Responsibility
http://aspalliance.com/526

..NET Data Access Performance Comparison
http://aspalliance.com/626

--
Teemu Keiski
ASP.NET MVP, Finland
"huzz" <hu**@discussio ns.microsoft.co m> wrote in message
news:50******** *************** ***********@mic rosoft.com...
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 "Unreachabl e
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. The timeout period elapsed prior to obtaining a
connection
from the pool. This may have occurred because all pooled connections were
in
use and max pool size was reached.

Also instead of adding this bit of code
[(ConfigurationS ettings.AppSett ings["DSN"]);
SqlCommand selectCmd = new
SqlCommand("sp_ DMListFiles",ob jConn)]
in every method.. how can i put it somewhere and reuse it in every
methods??

Many thanks in advance.

public SqlDataReader DMListFiles(int DepID, int FolderID)
{
SqlConnection objConn = new
SqlConnection(C onfigurationSet tings.AppSettin gs["DSN"]);
SqlCommand selectCmd = new
SqlCommand("sp_ DMListFiles",ob jConn);
selectCmd.Param eters.Add("@Dep ID",DepID);
selectCmd.Param eters.Add("@Fol derID",FolderID );
selectCmd.Comma ndType = CommandType.Sto redProcedure;
objConn.Open();
SqlDataReader dr = selectCmd.Execu teReader();
return dr;
}

Jul 21 '05 #2

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

Similar topics

8
2153
by: Pierson C | last post by:
I am developing on a website that is utilizing SQL Server 2000. Shortly after deploying the site, we began having timeout issues due to the max connections. 1st instinct was to diligently tidy up our connections. We did so by encapsulating with the using statement. Ex: using (SqlConnection myConnection = new SqlConnectionConfigurationSettings.AppSettings))
4
2054
by: Steve Richter | last post by:
I really miss c++ .... I have an SqlConnection object within my Web.UI.Page object. The thinking is that the connection to the database server is opened once when the page starts to do its thing, then when everything is rendered down to the browser, and all references to the page object are ended, the connection to the server can be closed. First of all, are the SqlConnection Open and Close methods quick performers and I dont need to...
3
4273
by: FC | last post by:
Hello All: I am getting the following error: Compiler Error Message: CS0246: The type or namespace name 'conn' could not be found (are you missing a using directive or an assembly reference?) This error point to the line conn.Close() on my finally statement. I am pretty new at this and I did not find much on the web. Any help would be greatly appreciated. My code is as follows: <%@ Page Language="C#" debug="true" %>
3
1534
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...
35
11403
by: Eric Sabine | last post by:
In my Finally block, I was using cn.close (where cn is an ADO.NET connection object, SQLConnection to be exact) and then I came across the following in some microsoft code. If Not cn Is Nothing Then CType(cn, IDisposable).Dispose() End If I have to admit, I'm not sure what happens here. Will someone explain this line of code (the middle one, not the if statement LOL) to me please?
1
210
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....
1
2402
by: John Bailo | last post by:
using ( SqlCommand cmd = new SqlCommand("select * sample"), new SqlConnection( sqlDsn ) ) ) { SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); adapter.Fill(dt);
6
1360
by: mavrick_101 | last post by:
do I need to explicitly do a Connection.Dispose() too? Thnx
8
14558
by: Imran Aziz | last post by:
Hello All, Like in C++ I tried to use constructor to open a database connection and distructor to close the database connection, it now turns out that one cannot create distrutors in C# classes. Here is my code public class DBLayer {
0
8683
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
9170
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
8871
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7739
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
5862
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
4371
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
4622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
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
2007
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.