0

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

2 回答 2

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

Also note that I have removed from your code the try/catch because you are not trying to handle anything there. You have just closed the connection, but the using statement will ensure that also in case of exceptions.

于 2013-03-29T21:17:41.283 回答
0

I found a work around. Use OledB instead and the Microsoft.Jet.OLEDB.4.0 Provider. No more file lock worries.

    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
于 2013-04-03T23:01:41.303 回答