没有正确关闭Odbc连接

本文关键字:Odbc 连接 | 更新日期: 2023-09-27 18:06:27

我有一个简单的测试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
    }

没有正确关闭Odbc连接

通常,一次性对象(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

还请注意,我已经从你的代码中删除了try/catch,因为你没有试图处理任何事情。您刚刚关闭了连接,但是using语句将确保在出现异常的情况下也关闭连接。

我找到了一个工作。请使用OledB和Microsoft.Jet.OLEDB.4.0提供程序。

    string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=X:'CMSBak'ISP;Extended Properties=dBASE IV;User ID=Admin;Password=;";
    DataSet ds = new DataSet();
    using(OleDbConnection conn = new OleDbConnection(connectionString))
    {
        conn.Open(); // Open the connection
        string strQuery = "SELECT * FROM ISPINMAS";
        var adapter = new OleDbDataAdapter(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