简体   繁体   English

使用IDisposable C#的MySQL连接

[英]MySQL Connection using IDisposable C#

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). 我正在使用ASP.net开发MySQL Web App,并且听说mysql连接应使用using指令,以确保在出现问题时始终关闭连接,因为它们不能保证数据库将从内部关闭最终声明是否已发生捕获(取决于异常)。

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. 我正在尝试创建一个打开MySQL连接的类,因此不必每次访问数据库时都重复相同的代码。

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 the connection needs to be an IDISOSABLe class but I am not sure how I can implement this. 我已经看到,被用来打开连接的类必须是IDISOSABLe类,但我不确定如何实现此类。 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 实现IDisposable接口的典型方法是遵循文档中示例中列出的模式: http : //msdn.microsoft.com/zh-cn/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 :) MSDN :)

http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx#Y800 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? 您正在使用哪种数据访问设计模式?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM