I am developing a MySQL Web App using ASP.net and I have heard that a using directive should be used for the mysql connection to ensure that the connection is always closed should something go wrong as their is no guarantee that the database will close from inside finally statement if a catch has occured (depending on the exception).
I am trying to create a class that opens the MySQL Connection so I haven't got to repeat the same code each time I need to access the database.
I have seen that it is something like
using (call class to open connection)
{
MySQL Stuff Here
}
I have seen that the class that is being called to open t开发者_JAVA技巧he connection needs to be an IDISOSABLe class but I am not sure how I can implement this. However, I cannot find any information on how this can be done. Thanks for your help.
The typical way to implement the IDisposable
interface is by following the pattern laid out in the example in the documentation: http://msdn.microsoft.com/en-us/library/system.idisposable.aspx
Basically, your class should/would look like this:
public sealed class YourClass : IDisposable
{
private MySqlConnection _Connection;
private bool _IsDisposed;
public YourClass()
{
_Connection = new MySqlConnection();
}
public void Dispose()
{
if (!_IsDisposed)
{
_Connection.Dispose(); // or Close
_IsDisposed = false;
}
}
}
There are numerous variants of this pattern, depending on whether you intend for others to inherit from your class, and whether you have any unmanaged resources you need to close (like file handles), but for normal use, the above is enough.
MSDN :)
http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx#Y800
However I'm not really sure what you are trying to achieve will be of any benefit to you. What is your wrapper class doing differently than just using the connection object
what data access design pattern are you using?
精彩评论