Arne Vajhøj a écrit :
esha wrote:
>Thank you.
If I'm not using multithreading (at least for now because to be able
to run I need to learn how to walk first) then what is a preferable
approach? - still local connection for every procedure? Or it will be
better to use a global one?
I can think of a few cases where a global database
connection will work.
I find it hard to come up with an example where it
is the best solution.
The general rule is:
- open as late as possible
- close as soon as possible
Arne
Hi,
You can have a "global" Connection instance and open it every time you
need it, and close it right after. I think it is the same as creating a
new connection from scratch every time, but perhaps slightly more
efficient as well as convenient.
But what if you open your connection and call a method that closes it
though you still want to work on it ? Well, you can open it again...
But what if you do not (or do not want to) know if the methods you call
will close your connection ? Well, you can use the DbConnectionAdapter
class (cf. end of the post). Then, EVERY time you want to open your
connection do the following :
using (DbConnectionAdapter c=new DbConnectionAdapter(myConnection))
{
c.Open();
// Do some work here
}
At the end of the scope, your connection will be in the state you found
it, i.e. opened or closed.
Mathieu
<code>
public class DbConnectionAdapter:
IDisposable
{
public DbConnectionAdapter(IDbConnection connection)
{
_Connection=connection;
_ConnectionState=connection.State;
}
~DbConnectionAdapter()
{
Dispose(false);
}
public void Close()
{
if (_Connection.State!=ConnectionState.Closed)
_Connection.Close();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Open()
{
if (_Connection.State!=ConnectionState.Open)
_Connection.Open();
}
protected void Dispose(bool disposing)
{
if (_Disposed)
return;
if (_Connection.State!=_ConnectionState)
switch (_ConnectionState)
{
case ConnectionState.Closed:
_Connection.Close();
break;
case ConnectionState.Open:
_Connection.Open();
break;
}
_Disposed=true;
}
private bool _Disposed;
private IDbConnection _Connection;
private ConnectionState _ConnectionState;
}
</code>