没有正确关闭Odbc连接

时间:2013-03-29 21:11:46

标签: 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
    }

2 个答案:

答案 0 :(得分:6)

像往常一样,当您不再需要时,应该丢弃一次性物品(OdbcConnectionusing statement在这种情况下非常有用

    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语句也将确保在异常的情况下。

答案 1 :(得分:0)

我找到了一个解决方法。使用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
相关问题