Do I need to use SqlConnection.Open() inside:
using (SqlConnection var = new SqlConnection())
{
//my operations
}
?
What happens if I don't dispose this connection by SqlConnection.Close() function?
Yes, you need to Open your connection inside the using block.
If you don't explicitly Close() the connection, the end of the using block will do it for you as the using disposes of the connection. When a connection is disposed it is automatically closed.
The using statement is just syntactic sugar which ensures that Dispose gets called on the IDisposable instance no matter what, so in your case using (SqlConnection connection = new SqlConnection()) is roughly equivalent to (as per MSDN):
SqlConnection connection = new SqlConnection();
try
{
// Operations.
}
finally
{
if (connection != null)
{
connection.Dispose();
}
}
In the case of SqlConnection Dispose and Close calls are actually equivalent, so a call to Close would be redundant within a using (SqlConnection) block.
Calling Open, on the other hand, will still be necessary in many scenarios (before a call to ExecuteReader, ExecuteScalar, ExecuteNonQuery, for example). The using statement has no effect on whether or not you need to explicitly open the connection - only on whether or not you need to explicitly close it.
Provides a convenient syntax that ensures the correct use of
IDisposable objects
using Implements IDisposable Internally
using(SqlConnection con=new SqlConnection("myCOnstr"))
{
con.open();
using(SqlCommand con=new SqlCommand("myCmd",con))
{
//......Insert/Update /Delete
}
}
Related
Is there a problem with the second usage(Code snippet 2)? If so, what is the problem?
// ---Code snippet 1---
IDbConnection connection = new SqlConnection(connStr)
using(connection)
{
connection.Open(); // Open a connection in “using”
todo...
}
// ---Code snippet 2---
IDbConnection connection = new SqlConnection(connStr)
connection.Open(); // Open a connection outside “using”
using(connection)
{
todo...
}
The using statement is just built-in language support for correct handling of IDisposable objects, using it you can make sure, that your disposable objects are disposed when they should be.
It basically translates to a try-finally pair, with a dispose call in the finally block.
You can read more about the using statement here.
That said, you should put the using keyword on the first statement you are creating the disposable object, so the correct version of your code would be:
using (var connection = new SqlConnection(connStr))
{
connection.Open(); // Open a connection in “using”
todo...
}
I don't think the placement of the using keyword makes any difference on what the connection object does or looks like.
I've been running into some problems concerning a SqlTransaction I'm using in my code. During my Googling I see many people using a using statement with a SqlTransaction.
What is the benefit and/or difference of using this type of statement with a SqlTransaction?
using (SqlConnection cn = new SqlConnection())
{
using (SqlTransaction tr = cn.BeginTransaction())
{
//some code
tr.Commit();
}
}
Currently my code looks like this:
SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["T3"]);
cn.Open();
SqlTransaction tr = cn.BeginTransaction();
try
{
//some code
tr.Commit();
cn.Close();
}
catch(Exception ex)
{
tr.Rollback();
cn.Close();
throw ex;
}
What is the advantage of one way over the other?
A using statement should be used every time you create an instance of a class that implements IDisposable within the scope of a block. It ensures that the Dispose() method will be called on that instance, whether or not an exception is thrown.
In particular, your code only catches managed exceptions, then destroys the stack frame by throwing a new exception instead of rethrowing the existing one.
The correct way to do it is:
using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["T3"])) {
cn.Open();
using (SqlTransaction tr = cn.BeginTransaction()) {
//some code
tr.Commit();
}
}
Note that if your class has instance members of types that implement IDisposable, then your class must implement IDisposable itself, and dispose of those members during its own Dispose() call.
The reason for this is that the SqlTransaction object will roll back in its Dispose() method if it was not explicitly committed (e.g. if an exception is thrown). In other words, it has the same effect as your code, just a little bit cleaner.
Essentially the using does the same thing that you are doing, except int a finally block instead of catching all exceptions:
using (SqlConnection cn = new SqlConnection())
{
using (SqlTransaction tr = cn.BeginTransaction())
{
//some code
tr.Commit();
}
}
is the same as, just much less code :)
{
SqlConnection cn = null;
try
{
cn = new SqlConnection();
{
SqlTransaction tr = null;
try
{
tr = cn.BeginTransaction())
//some code
tr.Commit();
}
finally
{
if(tr != null && tr is IDisposable)
{
tr.Dispose();
}
}
}
}
finally
{
if(cn != null && cn is IDisposable)
{
cn.Dispose();
}
}
}
In the end, using is just a shortcut for a pattern. But it's a very useful and helpful shortcut, because it ensures you implement the pattern correctly and means you can do it with less code.
In this case, you haven't implemented the pattern correctly. What happens in your code if the call to tr.RollBack() also throws an exception?
The using statement is closing and disposing your connection and transaction for you. It's the equivalent of having a finally block on your try/catch that does the dispose.
You could also condense the using blocks down a bit like this...
using (SqlConnection cn = new SqlConnection())
using (SqlTransaction tr = cn.BeginTransaction())
{
//some code
tr.Commit();
}
which would be roughly the same as:
SqlConnection cn = null;
SqlTransaction tr = null;
try
{
cn = new SqlConnection());
tr = cn.BeginTransaction());
//some code
tr.Commit();
}
finally
{
if (cn != null)
cn.Dispose();
if (tr != null)
tr.Dispose();
}
If you don't use a using() block, you'll have to explicitly call the .Dispose() method of the SqlConnection and SqlTransaction objects. If you fail to do that, then unmanaged resources will not be released and could cause memory leaks or other problems.
Using using gurantees that your connection object will be disposed after the code returns. Dispose is useful to release unmanages resources, As a good practice, if an object implements IDisposable, dispose method always should be called
In addition to all that, it prettifies your code. Doesn't the 7 lines of code look better than the 14 lines? I breath a sign of relief every time I see a using block. It's like that little squirt of mist that comes out of that glad smelly thing. Mmm, I'm a pretty block of efficient code. Look at how well I manage memory and how pleasing I am to the eye.
Here is my code:
public void InsertData()
{
using (SqlConnection connection = new SqlConnection(DBHelper.ConnectionString))
{
using (SqlCommand command = new SqlCommand("Some Simple Insert Query", connection))
{
connection.Open();
command.ExecuteNonQuery();
}
}
}
But I found this code sample:
public void InsertData()
{
SqlConnection connection = new SqlConnection(DBHelper.ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand("Some Simple Insert Query", connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
connection.Dispose();
}
why does the author use
command.Dispose()
and
connection.Dispose();
in their code?
using can only be used on objects that are disposable (which is when they implement the interface IDisposable). Doing so will automatically call Dispose on that instance. However in contrast to call it yourself the using-statement ensures that Dispose is also called when an exception whithin that block occurs. So it´s safer to use that approach.
Your first example is equivalent to this:
try
{
SqlConnection connection = new SqlConnection(DBHelper.ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand("Some Simple Insert Query", connection);
try
{
command.ExecuteNonQuery();
}
finally
{
command.Dispose();
}
}
finally
{
connection.Dispose();
}
You'll have resource leak when exception has been thrown:
public void InsertData()
{
SqlConnection connection = new SqlConnection(DBHelper.ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand("Some Simple Insert Query", connection);
command.ExecuteNonQuery(); // <- imagine that this throws exception
// and so these don't execute at all and you'll have two resources leaked:
// 1. Connection
// 2. Command
command.Dispose();
connection.Close();
connection.Dispose();
}
The reasons of the exception can vary:
1. Insert failed (e.g. invalid field value insertion)
2. User doesn't have privelege required
3. RDMBS Internal error
...
You can emulate using with try .. finally which is wordy:
public void InsertData()
{
SqlConnection connection = null;
try {
connection = new SqlConnection(DBHelper.ConnectionString);
connection.Open();
SqlCommand command = null;
try {
command = new SqlCommand("Some Simple Insert Query", connection);
command.ExecuteNonQuery();
}
finally { // rain or shine, dispose the resource (if it has been created)
if (command != null)
command.Dispose();
}
}
finally { // rain or shine, dispose the resource (if it has been created)
if (connection != null)
connection.Dispose();
}
You don't have to use dispose in your example, because the using block does that for you.
See here: using Statement (C# Reference)
He is using connection.Dispose(); because the person is inexperienced and is writing bad code that is not safe. If a exception is thrown the connection will never be disposed of causing it to remain open till the GC collects the connection maybe minutes or hours later.
The using block is just syntactic sugar for the try/finally Dispose() pattern. This is all explained in the documentation.
Note you can also reduce the indentation in your code:
using (SqlConnection connection = new SqlConnection(DBHelper.ConnectionString))
using (SqlCommand command = new SqlCommand("Some Simple Insert Query", connection))
{
connection.Open();
command.ExecuteNonQuery();
}
In .Net IDisposable and the Dispose method are used to clean up unmanaged resources.
.Net keeps track of managed resources so it can clean them up automatically, but it needs to have some help when dealing with unmanaged resources.
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
https://msdn.microsoft.com/en-us/library/system.idisposable.dispose(v=vs.110).aspx
The using statement is a way to automatically call the Dispose method when you're done using it.
Provides a convenient syntax that ensures the correct use of IDisposable objects.
It'll even get called if an exception is called.
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
https://msdn.microsoft.com/en-us/library/yh598w02.aspx
The code which isn't using the using statements is incorrect.
It'll work most of the time, but if an exception occurs the unmanaged resources in SqlConnection could be left uncleaned.
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement.
I have a program in C# where I created various class, and all of them need to make calls to the database. So I decided to create a static class that handles all the calls to allow me to apply far-reaching changes very easily. Within that class I have functions that call the various parts of SqlCommand (ExecuteReader(), etc) I finally got tired of rewriting all the connection code, and abstracted it out to another function called getSqlCommand() which just returns an initialized SqlCommand which I use to perform the various commands. I've chosen to not pass the SqlCommand back to the other programs (though it is a public method in case I need it) because there is some pre-processing if you will that I may do before I had the results back to the program.
My question is, if/when the SqlConnection closes? Since it is being passed back as a return value in a SqlCommand, will it be left open? and if so, can I close it? Here is some code (slightly stripped down) so you can see what I am doing, thanks in advance!
The function to create the SqlCommand:
public static SqlCommand GetSqlCommand(string query)
{
using (SqlConnection dbConnection = new SqlConnection( SQLConn )) {
dbConnection.Open();
SqlCommand cmd = new SqlCommand( query, dbConnection );
cmd.CommandTimeout = 0;
return cmd;
}
}
An example of the usage of the command in the static class:
public static SqlDataReader executeReader( string query )
{
try {
return GetSqlCommand(query).ExecuteReader();
} catch (SqlException) {
//Notify User and Resolve Error
}
return null;
}
A SqlConnection is closed when you call Dispose. Exiting the using block does that. The connection will be closed.
That's all there is to it. It will not magically stay open because ADO.NET does not know and cannot find out that you returned the connection object.
Move the connection out of the GetSqlCommand method. Pass the connection object into that method. GetSqlCommand has no business in creating a connection. It should take a connection, use it, but not close it.
The connection closes before the code exits the GetSqlCommand method. That means that the command object that it returns is useless.
The using construct creates a try ... finally block, where it disposes the connection at the end of the block. As disposing the connection also closes it, the connection is already closed before the command object is returned from the method to the caller.
The using keyword is equivalent to use try finally, and within the finally block your connexion will be disposed
SqlConnection dbConnection = new SqlConnection( SQLConn );
try
{
dbConnection.Open();
SqlCommand cmd = new SqlCommand( query, dbConnection );
cmd.CommandTimeout = 0;
return cmd;
}
catch(Exception ex)
{
}
finally
{
dbConnection.Dispose();
}
And even if there is a return statement inside a try block , the block finally will always be executed
I'm not sure if my question is clear so here's a code sample:
public static bool isRecordExist(int ID)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand command = new SqlCommand(commandText, connection))
{
int flag = int.Parse(command.ExecuteScalar);
if (flag)
return false;
else
return true;
}
}
}
So, now I understand that I don't need to close or dismiss any Sql objects when I have the 'using' keyword, because it does that automatically as soon as you get our of it's brackets but now the we reach to the 'return' part. will it dismiss and close the objects properly or do I need to save this value and make my check and 'return' outside the 'using' code ?
Yes it closes automatically. Exiting a using block calls .Dispose() on the object in question which for a SqlConnection will close the connection and any open resources.
Does End Using close an open SQL Connection
Yes, the connection will be closed.
Note that this can cause problems. Say, for example, that you want to return a DataReader from the function. As soon as you return the datareader, the connection that your reader depends on is closed by the using block and you can't read any records. In those situations, I use either a delegate or an iterator block to get around the problem, depending on what I'm doing.
Yes, the object will be disposed properly. If you take a look at the IL generated from the method, you will see a try/finally block in the appropriate spots of your using { ... } statements. Exiting the method from any part inside of a using { ... } block will always follow the try/finally dispose pattern.
I also would recommend stacking your using statements like this:
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(commandText, connection))
{
//some work
}
It generally makes the code more readable, especially if you are using 4 or 5 of them.
Yes, because it is syntactic sugar for try/finally without the catch.
So when you do this:
using (SqlConnection connection = new SqlConnection ...) {
code code code then return;}
You get (approximately) this behind the scenes:
SqlConnection connection;
connection = null;
try
{
connection = new SqlConnection ...;
code code code then return;
}
finally
{
if (connection != null) connection.dispose();
}
And by the definition of finally, it is always called, no matter how you break out of the try block (usually you think 'exception' but also including return).