What if i don't close database connection in disconnected mode - c#

I am doing windows forms application with connection to SQL Server (disconnected mode). Every action I handle in my application needs the connection. So I don't know where to close the connection.
I am asking what if i don't close the connection. I know that there is no runtime error that appears. But is there any other error that could appear?

There is a risk that if you are using the same connection for each method, from a private field or GetConnection() method etc.; you could end up trying to read/write when the connection is still open.
This could then throw errors and you could end up in a whole heap of it, if using a live SQL database.
If you can, create a new instance of a connection in a using statement each time you want to access the DB.
Like this:
var connectionString = "YourConnectionStringToTheDB";
var queryString ="YourSQLQueryHere"; // FROM * IN tbl SELECT * etc...
using (SqlConnection connection = new SqlConnection(
connectionString))
{
using (SqlCommand command = new SqlCommand(queryString, connection))
{
command.Connection.Open();
command.ExecuteNonQuery();
}
}
This way it is closed and disposed of when the code runs outside of the using statement's scope.
Notice that the SqlCommand is also in a using statement, as it too can be disposed of.
This is cleaner code and marks the objects for disposal by the Garbage Collector. (Google is your friend) - BIG topic; a lot of stuff to read.
Here is a similar question which gives you some more detail: The C# using statement, SQL, and SqlConnection
EDIT
Better still, you could wrap your SQL code in a try { } catch { } block to handle any errors at runtime.

Related

Closing an OleDbConnection

Just a general question, if I open an OleDbConnection in my program, should I close it at some point? I only ask because I've seen a few tutorials where the presenter doesn't include a statement to close the connection.
In my specific circumstances, I open a connection to access an Excel file, fill a DataTable and grab some values. After that though, there is no reason for me to have the connection open and I'm thinking it would probably cause some issues if I left it open.
Also, is the statement conn.Close(); sufficient to close the connection?
Yes, you should close your connection as soon as you are done with it. If you use your connection in one method and not immediately after it again, close and dispose it, so it can be cleaned up.
You should wrap the creation of a connection in a using statement since that will even close and dispose the connection when an exception occurs.
using (OleDbConnection conn = new OleDbConnection(...))
{
// use the connection inside here
}
You should make use of the using block which will ensure the connection is closed and disposed correctly.
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
//Do some work
}//The connection is automatically closed when the code exits the using block.
Further reading here

SQL Connection Open Exception

I am working on a project which, up until today, has been fine. However now when I run it and it goes through a few different Stored Procedure calls it is throwing an InvalidOperationException with the message The connection was not closed. The connection's current state is open.
I get that I could put in a check to see if the connection is already open, but this code hasn't changed (it is under Version Control and isn't modified) so I'm looking for other potential explanations.
Could there be some lock in SQL which isn't being released? Is there a process which I should look out for and kill?
I can't really post the code as there is a lot of it, and it is split up into smaller methods which makes it harder to pull out individual items. E.g:
public SqlConnection Connection
{
get
{
this._connection.Open();
return _connection;
}
}
public IDataReader RetrieveRecord(int Id)
{
//SP
SqlCommand cmd = this.Connection.CreateCommand();
cmd.CommandText = "SelectRecord";
cmd.CommandType = CommandType.StoredProcedure;
//Parameters
cmd.Parameters.Add(new SqlParameter("#tID", Id));
//instruct the data reader to close its connection when its Close method is called by passing the CommandBehavior.CloseConnection
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
Nothing massively complex, I just don't understand why this connection is now throwing an exception.
The DAL is not stable enough:
You open a Connection that is not closed if something goes wrong in RetrieveRecord.
You should create a new connection inside RetrieveRecord and close it there in a finally block.
Opening a connection is cheap thanks to Connection Pooling.
Problem is with the line
this._connection.Open();
Because you are trying to open an already opened connection.
Try this to check before opening a connection:
if (this._connection.State == ConnectionState.Closed)
this._connection.Open();
Sorted. Two reboots cleared whatever was keeping the connection open.
When you are talking about killing process, I think you know c# well.
You should always use
using()
{
}
Like:
using(SqlConnection con=new SqlConnection("connectionString"))
{
// Do something with con
using(SqlCommand cmd=new SqlCommand("cmdText",con))
{
// Do something with cmd
}
}
You know that SqlCommand and SqlConnection implement IDisposable
So when you put those objects within using, the connection closing and clean up job is automatically done.
No need to close the connection manually in the code, since using will do the work for you.

Safest DB connection in c# ASP.NET

I'm refactoring some old code as we're periodically having connection pool issues on a clients site.
While some code has wrapped DB connections in try/catch blocks I'll be using the using(){} thing (is there a proper term for this?)
So I'd like some clarification on how to use it in our situation to make as few changes as possible.
What we currently have is (mostly) something like this:
SqlConnection sqlConn = new SqlConnection();
SqlCommand sqlCmd = new SqlCommand();
try
{
// DB stuff here
}
finally
{
sqlCmd.Dispose();
sqlConn.Dispose();
}
Some connections aren't wrapped up at all.
So, I'm thinking of changing it to this:
using (SqlConnection ThisConnection = new SqlConnection(ConnectionString))
{
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = ThisConnection;
// DB stuff here
}
}
I've tried this and it works. But I know there's a difference between something working and something working well :)
So, a few questions:
If the SqlConnection is assigned to SqlCommand.Connection and I only wrap up the SqlCommand in a using, will the connection be closed and disposed then the SqlCommand is?
If not, is the above code ok? Or should the SqlCommand using be before the SqlConnection or does it not matter?
When the object is disposed at the end of the using is this absolutely guaranteed to close the DB connection?
All feedback greatly appreciated, cheers.
The using approach is preferable; much harder to get it wrong and leave scenarios where objects can escape without being disposed. Unless you have a very specific reason, it should be your default. You can reduce the nesting, though:
using (SqlConnection ThisConnection = new SqlConnection(ConnectionString))
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = ThisConnection;
// DB stuff here
}
When the object is disposed at the end of the using is this absolutely guaranteed to close the DB connection?
It will dispose it; the underlying connection (via any of these approaches) will usually still be pooled, though.
Of course, I also submit that the easiest way to do this is to use less code - less to get wrong. For example, I'd be very tempted to use "dapper", which avoids the need to mess with the commands, readers, parameter collections, etc:
int id = 123;
string name = "abc";
using (var conn = new SqlConnection(ConnectionString))
{
conn.Execute("Some TSQL", new { id, name });
}
if you dispose your connection, you need dispose your command, calling Dispose on it will supress the call to the finalizer. Add using command after using conenction
Don't set your command before connection
Yes, because you close your not managed object , who is coonnection
Remark : using bloc is preferred that try catch finally for basic need without custom treatment in catch bloc
msdn sample link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlconnection(v=vs.110).aspx
this article don't treat using command but speak about connection

Start and close SQL connection - At start and in the end or every time needed?

I'm making a web application in C# with ASP.Net, and I'm using an SQL database for it. In the guides I saw (about SqlConnection and SqlCommand) they open and close the SQL connection each time they want to send a query. But I'm not sure this is the best way to handle the connection, because I also learned some PHP, and as far as I know in PHP you open a connection only once, at start. So what is the best way to handle the connection?
You should generally have one connection, and transaction, for the length of the web request.
If you have two connections, you could potentially have inconsistent data. e.g. in the first query you check the bank balance, then you close it. You then add $5 to the balance and save that away in the next connection. What if someone else added $5 between the two connections? It would go missing.
The easiest thing to do is to open the connection global.asax BeginRequest and save that away into the HttpContext. Whenever you need a connection, pull it from there. Make sure that you .Close the connection in your EndRequest
Also, read up here on connection pooling: http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx
It is not 'expensive' to repeatedly open and close connections, provided the username is the same each time.
Ado.Net has connection pooling already managed for you, so you don't need to worry about reusing connections.
You could use the Using statement to close and dispose connection:
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection("my_connection_string"))
{
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * from Table", conn))
{
conn.open();
adapter.Fill(dt);
}
}
Normal practice in .NET is to open a SqlConnection and use a SqlCommand, then dispose of both of them.
using(SqlConnection connection = new SqlConnection("myConnectionString"))
{
using(SqlCommand command = new SqlCommand("dbo.SomeProc"))
{
// Execute the command, when the code leaves the using block, each is disposed
}
}
As a connection to database is an expensive resource it's better to open sql connection as late as possible and close early. So you should open the connection just before executing a command and close it once you have executed it.
On the other hand if you are going to execute many commands in a short interval of time it's better to open the connection once and close after all the commands are executed.
For starters they do not as there is a connection pool that is being used, but SqlCommand has an overload to take a connection object, so you could keep the connection around and pass it.
Generally:
using (var ts = new TransactionScope())
{
using (var connection = new SqlConnection(...))
{
using (var command = new SqlCommand(connection, ...)
{
...
}
using (var command = new SqlCommand(connection, ...)
{
...
}
}
ts.Complete();
}
Of course I would recommend using LINQ-to-SQL or EF at this point.
Try Data Access Application Block in the Enterprise Library if you do not want to worry about opening and closing the connections.

C# SQL Distributed transaction completed. Either enlist this session in a new transaction or the NULL transaction

I'm getting this error (Distributed transaction completed. Either enlist this session in a new transaction or the NULL transaction.) when trying to run a stored procedure from C# on a SQL Server 2005 database. I'm not actively/purposefully using transactions or anything, which is what makes this error weird. I can run the stored procedure from management studio and it works fine. Other stored procedures also work from C#, it just seems to be this one with issues. The error returns instantly, so it can't be a timeout issue. The code is along the lines of:
SqlCommand cmd = null;
try
{
// Make sure we are connected to the database
if (_DBManager.CheckConnection())
{
cmd = new SqlCommand();
lock (_DBManager.SqlConnection)
{
cmd.CommandText = "storedproc";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Connection = _DBManager.SqlConnection;
cmd.Parameters.AddWithValue("#param", value);
int affRows = cmd.ExecuteNonQuery();
...
}
}
else
{
...
}
}
catch (Exception ex)
{
...
}
It's really got me stumped. Thanks for any help
It sounds like there is a TransactionScope somewhere that is unhappy. The _DBManager.CheckConnection and _DBManager.SqlConnection sounds like you are keeping a SqlConnection hanging around, which I expect will contribute to this.
To be honest, in most common cases you are better off just using the inbuilt connection pooling, and using your connections locally - i.e.
using(var conn = new SqlConnection(...)) { // or a factory method
// use it here only
}
Here you get a clean SqlConnection, which will be mapped to an unmanaged connection via the pool, i.e. it doesn't create an actual connection each time (but will do a logical reset to clean it up).
This also allows much more flexible use from multiple threads. Using a static connection in a web app, for example, would be horrendous for blocking.
From the code it seems that you are utilizing an already opened connection. May be there's a transaction pending previously on the same connection.

Categories