Working on "using" statement in ADO.NET - c#

I want to properly dispose the SqlConnection object whenever i come out of the method. So im using the "using" statement as shown below.
public int Hello()
{
using(SqlConnection con=new SqlConnection(constring))
{
using(SqlCommand cmd=new SqlCommand(Query,con))
{
try
{
con.Open();
return cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
throw ex;
}
finally
{
con.Close()
}
}
}
}
Now, what i want to know is, Will the above code
Dispose the Connection properly when an Exception is occured in ExecuteNonQuery.
Make sure we will not get any ConnectionPool issues
Make sure the data is returned properly
If an exception occurs in SqlConnection will it dispose the object?
Can anyone help me on this?

You don't need the try/catch if you're just going to throw it, just change your code to this:
public int Hello()
{
using(SqlConnection con=new SqlConnection(constring))
{
using(SqlCommand cmd=new SqlCommand(Query,con))
{
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
and regardless of what happens, exception or not, the connection will get closed if it's open and disposed.

Dispose the Connection properly when an Exception is occured in ExecuteNonQuery.
Yes
Make sure we will not get any ConnectionPool issues
i guess you mean connections would be properly relieved after executing query. if that is your question than You should not by using this approach.
Make sure the data is returned properly
using has nothing to do with returning data
If an exception occurs in SqlConnection will it dispose the object?
Yes
though you can rewrite your code as
using(SqlConnection con=new SqlConnection(constring))
{
using(SqlCommand cmd=new SqlCommand(Query,con))
{
try
{
con.Open();
return cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
throw;
}
}
}

You should not use the using statement for sqlconnection.
using(SqlConnection con=new SqlConnection(constring))
Better you use try,catch and finally block to close the connection. So even if exception occurs in try & catch the finally block will execute and close the connection if its open.
The reason behind this is, think of below situaion.
Create object of a class that handles all database operation
e.g. DBUtility objDB = new DBUtility()
the above statement creates object of class and also initializes the sqlconnection variable from the constructor.
Now i am using the object objDB for executing multiple queries one by one. For this it should initialize the sqlconnection object only once and use it for its whole life (life obj objDB).
In your case the sqlconnection will be initialized as and when the method is called.
So simply init the connection once and open/close it for each of your operations. Your connection will automatically disposed by Garbage collector when objDB is disposed.

Related

Connection does not close like it should

I am encountering the following error in my ASP project:
The connection was not closed. The connection's current state is open
While calling the .open() function on a SqlConnection Object.
I have tried this :
if (Conn.State != ConnectionState.Closed)
{
Log.Message(xxx);
try
{
Conn.Close();
}
catch (Exception ex)
{
Log.Error(xxxx);
}
}
Conn.Open();
But this still raises the error. The Conn object is declared as:
private static readonly SqlConnection Conn = new SqlConnection(xxxx);
Any idea where I should look for a solution
Here's the pattern.
using(var conn = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(someSql, conn)
{
conn.Open();
cmd.ExecuteNonQueryOrWhatevs();
}
Create your connection
Open your connection
Dispose of your connection
Don't try to reuse it. Just get it, use it, and dispose of it as fast as possible.
Also, none of this is thread safe, so don't be touching any of the above instances from different threads. One thread to use the connection only, please. Feel free to use multiple threads to process the results.
To ensure that connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Do work here; connection closed on following line.
}
The best way to close the connection and disposed object is 'Finally' you should go for it.
OR better to use Using to dispose all objects and close connections see below snippet
public void run_runcommand(string query)
{
using(var con = new SqlConnection(connectionString))
{
using(var cmd = new SqlCommand(query, con))
{
con.Open();
// ...
}
} // close not needed since dispose also closes the connection
}

How to work with many connection in c# and ASP.NET?

This is how I do my connection
SqlConnection conn = new SqlConnection(connectionstring);
conn.open();
SqlCommand comando = new SqlCommand(/*my query update/delete/insert/select o execute sp*/,conn);
comando.Parameters.Add("#parameter1","value1")
comando.Parameters.Add("#parameter2","value2")
comando.Parameters.Add("#parameterN","valueN")
comando.ExecuteNonQuery()
conn.close();
but server administrator says there are many connections.
Then, how can I execute my queries?
Would it be better if I do not close the connection?
No, it would not be better to leave the connection open. Use "using" commands to manage system resources.
using(SqlConnection conn = new SqlConnection(stringconection))
{
conn.Open();
SqlCommand comando = new SqlCommand(/*my query update/delete/insert/select o execute sp*/,conn);
comando.Parameters.Add("#parameter1","value1");
comando.Parameters.Add("#parameter2","value2");
comando.Parameters.Add("#parameterN","valueN");
comando.ExecuteNonQuery();
}
Here is a quote from the documentation:
It is recommended that you always close the Connection when you are finished using it in order for the connection to be returned to the pool. This can be done using either the Close or Dispose methods of the Connection object. Connections that are not explicitly closed might not be added or returned to the pool. For example, a connection that has gone out of scope but that has not been explicitly closed will only be returned to the connection pool if the maximum pool size has been reached and the connection is still valid.
You can use "using" like Mark mentioned above (my preference). You can also use a try-catch-finally block.
try
{
SqlConnection conn = new SqlConnection(stringconection);
conn.Open();
SqlCommand comando = new SqlCommand(/*my query update/delete/insert/select o execute sp*/,conn);
comando.Parameters.Add("#parameter1","value1");
comando.Parameters.Add("#parameter2","value2");
comando.Parameters.Add("#parameterN","valueN");
comando.ExecuteNonQuery();
}
catch(Exception ex)
{
// catch exceptions here
}
finally
{
if(comando != null)
{
comando.Dispose();
}
if(conn != null)
{
conn.Dispose();
}
}

ADO.NET Funny Connection Pool Behaviour when bury SQL Exception

I am catching a sql exception and not rethrowing it. This seems to mean that the connection is not returned to the pool as I would expect. Is this possible?
using (IDbCommand paymentCommand = this.Connection.CreateCommand())
{
try
{
//database stuff
}
catch (SqlException ex)
{
//LOG CALL
}
}
why don't you put using(...){} inside try{} block? This way even if exception is thrown, using block will dispose off IDBcmd obj.
It's not clear in your question how you are creating the connection, but you do need to make sure you Open it, then Close it, regardless of errors or not.
Typically I'll do something like this:
SqlConnection connection = null;
try {
connection.Open();
// Do stuff like run a query, setup your IDbCommand, etc.
} catch (Exception ex) {
// Log error
} finally {
if (connection != null) {
connection.Close();
}
}
This way, no matter what happens, your connection will be closed and returned to the pool. If you fail to Close(), you'll "leak" that connection and eventually run out of pooled connections to draw from. The lifetime of the connection should generally only be as long as it takes to issue your sql command, at which point you should be closing it.
It's not clear what you are experiencing with the connection pool. However, I would definitely wrap your connection in a using statement.
This is what I usually use (note that dac.GetConnection() is simply a class that centralizes the code to get a connection object):
using (SqlConnection connection = dac.GetConnection())
{
using (SqlCommand command = new SqlCommand("myProc", connection))
{
command.CommandType = CommandType.StoredProcedure;
try
{
connection.Open();
//add params, run query
}
catch (Exception ex)
{
//handle/log errror
}
finally
{
if (connection.State == ConnectionState.Open)
connection.Close();
}
}
}

Is Close on database connection calling here?

I got this code:
try
{
using (OracleConnection c = new OracleConnection(globalDict[byAlias(connAlias)].connString))
{
c.Open();
using (OracleCommand recordExistentQuery = new OracleCommand("regular.IsExistent", c))
{
// here working on oraclecommand
}
}
} catch(Exception exc) { }
OracleConnection is class of devArt dotConnect for Oracle.
Will this code call c.Close() when it goes out of (OracleConnection c = new OracleConnection(globalDict[byAlias(connAlias)].connString)) { .... } ?
No, it will call Dipose(). A using block will implicitly call Dispose() on the object specified in the using statement.
But often times for a database connection, Dispose() handles the Close() functionality, releasing the connection/processId that keeps a connection.
I would also like to add that in the event of an exception somewhere in your //here working on oraclecommand (basically inside your using(...){ } statement, Dispose() will also be called.
By design, you should be able to make multiple to calls to an object implementing IDisposable. In your case, issuing a calling a call to Close() after your using block of code will simply do nothing, as the connection has already closed/been returned to the pool. Any additional calls after the object has cleaned up should just return and do nothing.

basic about "using" construct

If I use "using" construct, I know that the object gets automatically disposed. What happens if a statement inside an "using" construct raises an exception. Is the "using" object still disposed? If so, when?
A using block is converted - by the compiler - to this:
DisposableType yourObj = new DisposableType();
try
{
//contents of using block
}
finally
{
((IDisposable)yourObj).Dispose();
}
By putting the Dispose() call in the finally block, it ensures Dispose is always called - unless of course the exception occurs at the instantiation site, since that happens outside the try.
It is important to remember that using is not a special kind of operator or construct - it's just something the compiler replaces with something else that's slightly more obtuse.
This article explains it nicely.
Internally, this bad boy generates a try / finally around the object being allocated and calls Dispose() for you. It saves you the hassle of manually creating the try / finally block and calling Dispose().
Actually Using block is Equivalent to try - finally block, Which ensures that finally will always execute e.g.
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("Command", con))
{
con.Open();
cmd.ExecuteNonQuery();
}
}
Equals to
SqlConnection con = null;
SqlCommand cmd = null;
try
{
con = new SqlConnection(ConnectionString);
cmd = new SqlCommand("Command", con);
con.Open();
cmd.ExecuteNonQuery();
}
finally
{
if (null != cmd);
cmd.Dispose();
if (null != con)
con.Dispose();
}

Categories

Resources