OleDbConnection:如何使用函数打开和关闭连接

OleDbConnection: How to open and close a connection using a function

我有一个连接到 Excel 文件的函数:

    public OleDbConnection connection;

    public void eConnection(string srcString, string id)
    {
        conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + srcString + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
        connection = new OleDbConnection(conString);
        connection.Open();

    } 

我想创建另一个函数,在调用或调用时关闭此现有连接

这是我必须尝试关闭现有连接的方法:

    public void eCloseConnection()
    {
        connection.Close();
    }

如何使用调用同一连接并将其关闭的函数关闭现有连接

如何测试连接是否关闭?

不要这样。 OleDbConnection implements the IDisposable interface should be disposed as soon as you are done using it, and the best way to do it is to use it as a local variable declared in a using 声明:

public void DoStuffWithExcel(string srcString)
{
    conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + srcString + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
    using(var connection = new OleDbConnection(conString))
    {
        connection.Open();
        // do your stuff here...
    }
}

using 语句确保即使在 using 块内发生异常也能正确处理连接。
这种方式是最好的防止内存泄漏的方式,也是使用连接池的方式。

来自 Microsoft 文档页面 OLE DB, ODBC, and Oracle Connection Pooling

We recommend that you always close or dispose of a connection when you are finished using it in order to return the connection to the pool. Connections that are not explicitly closed may not get 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.

不要将连接的全局对象隐藏在 class 中。这增加了比解决的问题更多的问题。您应该跟踪该代码被调用了多少次以及它创建了多少个连接。当然,这会使结束部分变得更加复杂。

相反,C# 语言提供了解决此类问题的更好方法。一种特别适用于需要尽快将非托管资源释放给 OS 的连接等对象的方法。

如果您想要一个 class 来处理您的连接,或者如果您只想打开并使用一个连接

,您应该使用这种方法
public static class DbUtility
{
    public static OleDbConnection eConnection(string srcString)
    {
        conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + srcString + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
        connection = new OleDbConnection(conString);
        connection.Open();
        return connection;
    } 
    .... other static utilities
}

现在你可以这样使用你的class

string srcFile = @"d:\temp\myFile.xlsx";
using(OleDbConnection cn = DbUtility.eConnection(srcFile))
{
     .. use your connection

} // <- at this point your connection is automatically closed and disposed.

using keyword 当您需要销毁一次性对象(如连接)时非常有用。通过这种方式,您不需要时就不会保留全局对象。