[英]Not closing Odbc connection correctly
我有一個簡單的測試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
}
與往常一樣,當您不再需要一次性對象( 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.