没有正确关闭Odbc连接

Ran*_*ndy 0 c# odbc dbase

我有一个简单的测试Windows窗体应用程序.我第一次在VS中运行它一切正常.如果我再次立即运行它会在adapter.fill(ds)上抛出有关读保护内存的异常; 线.如果我等待5分钟左右,应用程序将再次运行.我想从stackoverflow社区获得一些关于我被愚弄的建议.我想这是一些连接超时.代码如下:

C#

    public void Button1_Click(object sender, EventArgs e)
    {
        string connectionString = @"Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;Dbq=x:\CMSBak\ISP;";

        var conn = new OdbcConnection(connectionString);

        conn.Open(); // Open the connection

        string strQuery = "SELECT * FROM ISPINMAS";

        var adapter = new OdbcDataAdapter(strQuery, conn);

        var ds = new DataSet();

        try
        {
            adapter.Fill(ds);
        }
        catch (Exception)
        {
            conn.Close();
            throw;
        }

        DataTable dt = ds.Tables[0];

        dataGridView1.DataSource = dt.DefaultView;

        conn.Close(); // That's it, now close the connection
    }
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 6

像往常一样,OdbcConnection当您不再需要时,应该丢弃一次性物品().
using语句会在这种情况下非常有帮助

    DataSet ds = new DataSet();
    using(OdbcConnection conn = new OdbcConnection(connectionString))
    {
        conn.Open(); // Open the connection
        string strQuery = "SELECT * FROM ISPINMAS";
        var adapter = new OdbcDataAdapter(strQuery, conn);
        adapter.Fill(ds);
    }
    // At this point the connection is closed and dispose has been called to 
    // free the resources used by the connection
    DataTable dt = ds.Tables[0];
    dataGridView1.DataSource = dt.DefaultView;
    // No need to close the connection here
Run Code Online (Sandbox Code Playgroud)

另请注意,我已从代码中删除了try/catch,因为您没有尝试处理任何内容.您刚刚关闭了连接,但using语句也将确保在异常的情况下.