Hi
I have some code in C# for accessing a database. For example:
using (SqlConnection conn = GetConnection() )
{
using (SqlCommand command = new SqlCommand( ...
{
...
}
}
(The function GetConnection just delivers the appropriate connection object,
and of course there is a lot of code snipped).
My question concerns the "using" statement. I just want to be sure that my
understanding is correct: it is not necessary for me to explicitly close
these database resources because the using statement ensures that these
objects have a Dispose function which is called, and these take care of
cleaning up? (Even if an exception is thrown?)
Thanks,
Peter 4 2233
Yes, that is correct
Regards
Richard Blewett - DevelopMentor http://www.dotnetconsult.co.uk/weblog http://www.dotnetconsult.co.uk
Hi
I have some code in C# for accessing a database. For example:
using (SqlConnection conn = GetConnection() )
{
using (SqlCommand command = new SqlCommand( ...
{
...
}
}
(The function GetConnection just delivers the appropriate connection object,
and of course there is a lot of code snipped).
My question concerns the "using" statement. I just want to be sure that my
understanding is correct: it is not necessary for me to explicitly close
these database resources because the using statement ensures that these
objects have a Dispose function which is called, and these take care of
cleaning up? (Even if an exception is thrown?)
Thanks,
Peter
[microsoft.publi c.dotnet.langua ges.csharp]
"Peter Kirk" <pk@alpha-solutions.dk> wrote in message
news:O6******** ******@tk2msftn gp13.phx.gbl... My question concerns the "using" statement. I just want to be sure that my understanding is correct: it is not necessary for me to explicitly close these database resources because the using statement ensures that these objects have a Dispose function which is called, and these take care of cleaning up? (Even if an exception is thrown?)
Thanks, Peter
Yes, Peter. The using keyword is a shorthand for a try finally block which
calls Dispose. Dispose will call Close.
Hence, the connection will be closed even if your code throws an exception.
Better yet, you don't need nested using-statements for each sql-object. The
sql client classes are pretty smart.
If you create a connection in using block, create a command, hook it to your
connection and then perhaps call ExecuteReader you don't need to dispose all
those objects. The SqlConnection will not only dispose itself but the
command and the reader as well.
Hence, one using statement would be sufficient.
Happy Coding
- Michael S
Although it's not a bad idea to explicitly close the other objects - command,
reader, or whatever.
Also you might get better performance by only calling Close vs. Dispose,
especially if your app has a lot of interaction with the database -
SqlConnection may reuse the connection - calling Dispose definatly kills the
connection and destroy's the object, meaning that a new one must be created
each time.
"Michael S" wrote: "Peter Kirk" <pk@alpha-solutions.dk> wrote in message news:O6******** ******@tk2msftn gp13.phx.gbl... My question concerns the "using" statement. I just want to be sure that my understanding is correct: it is not necessary for me to explicitly close these database resources because the using statement ensures that these objects have a Dispose function which is called, and these take care of cleaning up? (Even if an exception is thrown?)
Thanks, Peter
Yes, Peter. The using keyword is a shorthand for a try finally block which calls Dispose. Dispose will call Close.
Hence, the connection will be closed even if your code throws an exception.
Better yet, you don't need nested using-statements for each sql-object. The sql client classes are pretty smart. If you create a connection in using block, create a command, hook it to your connection and then perhaps call ExecuteReader you don't need to dispose all those objects. The SqlConnection will not only dispose itself but the command and the reader as well.
Hence, one using statement would be sufficient.
Happy Coding - Michael S
Why oh why oh why does this myth persist.
Here is the code for SqlConnection.D ispose reverse engineered via Reflector
protected override void Dispose(bool disposing)
{
if (disposing)
{
switch (this._objectSt ate)
{
case ConnectionState .Open:
{
this.Close();
break;
}
}
this._constr = null;
}
base.Dispose(di sposing);
}
In other words, if the connection is open it closes it, then it nulls out the connection string. All this means is you can't call
Open on that instance without reseting the connection string. The underlying connection just returns to the pool as with Close.
Whoever started the rumour that the connection is somehow removed from the pool / permanently closed or
whatever has alot to answer for.
Regards
Richard Blewett - DevelopMentor http://www.dotnetconsult.co.uk/weblog http://www.dotnetconsult.co.uk
Although it's not a bad idea to explicitly close the other objects - command,
reader, or whatever.
Also you might get better performance by only calling Close vs. Dispose,
especially if your app has a lot of interaction with the database -
SqlConnection may reuse the connection - calling Dispose definatly kills the
connection and destroy's the object, meaning that a new one must be created
each time. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Enos Meroka |
last post by:
Hallo,
I am a student doing my project in the university.. I have been trying
to compile the program using HP -UX aCC compiler, however I keep on
getting the following errors.
=================================================================
Error 19: "CORBAManagerMessages.h", line 4 # Unexpected 'std'.
using std::string;
^^^
|
by: Mike L |
last post by:
Should the command call "using" be before or after my namespace?
**AFTER**
namespace DataGridBrowser
{
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
|
by: xzzy |
last post by:
I was wondering why we have to have
using System.Data
using System.Configuration
using etc....
why are they not all lumped into one 'using'?
In other words, is there a best way to use project classes with 'using'
meaning
|
by: pmud |
last post by:
Hi,
I need to use an Excel Sheet in ASP.NET application so that the users can
enter (copy, paste ) large number of rows in this Excel Sheet. Also, Whatever
the USER ENETRS needs to go to the SQL DATABASE, probably by the click of a
button.
Is this possible? & what is the BEST APPROACH for doing this? & also if any
links are there do tell those to me too coz I have no idea how to go about
doing it.
|
by: acb |
last post by:
Hi,
I wrote a DLL Component (using Visual Studio 2005) and managed to
include it into a C# Console application.
I am now trying to include this component into a Web project. I copy
the DLL into the bin directory but am not able to progress. Can anyone
please guide me to an online tutorial on the subject.
Thanks,
| |
by: Metal2You |
last post by:
I'm working on an ASP.NET 2.0 application in Visual Studio 2005 that
accesses a Sybase database back end. We're using Sybase SQL Anywhere
9.0.2.3228. I have installed and registered the Sybase .NET 2.0
DataProvider (iAnywhere.Data.AsaClient.dll) into the GAC so it can be
used in the ProviderName property of a SQLDataSource and loads properly
at run time.
The application I'm writing is a bit more complex than the example I'm
about to...
|
by: mg |
last post by:
I'm migrating from VB6 and have a question about using 'Using' and the
best way to use it.
Here is a example of a small bit of code:
dbConx("open")
Using CN
Dim CMD As New OleDbCommand(sSQL, CN)
Dim DR As OleDbDataReader = CMD.ExecuteReader()
|
by: Eugene Anthony |
last post by:
The problem with my coding is that despite removing the records stored
in the array list, the rptPages repeater
control is still visible. The rptPages repeater control displayes the
navigation link (1,2,3 so on). The code can be found in
SubscriptionCart.aspx.cs.
Default.aspx
------------
|
by: JDeats |
last post by:
I have some .NET 1.1 code that utilizes this technique for encrypting
and decrypting a file.
http://support.microsoft.com/kb/307010
In .NET 2.0 this approach is not fully supported (a .NET 2.0 build
with these methods, will appear to encrypt and decrypt, but the
resulting decrypted file will be corrupted. I tried encrypting a .bmp
file and then decrypting, the resulting decrypted file under .NET 2.0
is garbage, the .NET 1.1 build works...
|
by: =?Utf-8?B?U2hhd24gU2VzbmE=?= |
last post by:
Greetings! I was researching AJAX to provide a solution to displaying status
messages while a long process executed. I found several examples online and
was able to use their code to get a quick application working. However, when
attempting to implement the solution, the AJAX calls weren't updating the
screen like the examples were and seemed not to fire until after the long
running process had completed.
I found the only real...
|
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...
| |
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...
|
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,...
|
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...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
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
|
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...
| |