我有一个Access数据库,正在使用OleDb进行连接。 连接和使用都很顺利,但我需要备份文件。
我正在关闭连接:
public class myDbHandlerClass
{
private OleDbConnection myConnection;
//in reality this string gets built by properties to the class
//it ends up being this...
//Yes Jet 4.0 this is an Access 2003 database
private string myConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=myDatabase.mdb";
public void OpenDatabase()
{
//to open the database
try
{
// Does a previous connection exist?
if ((myConnection != null) && myConnection.State != ConnectionState.Closed) return;
//No database connection string is specified, can't continue
if (string.IsNullOrEmpty(myConnectionString)) return;
myConnection = new OleDbConnection(myConnectionString);
myConnection.Open();
}
catch (Exception ex)
{
ExTrace.WriteLineIf(TraceLog.TraceError, ExTrace.ShowException(ex));
}
}
public void CloseDatabase()
{
try
{
if ((myConnection == null)) return;
if (myConnection.State != ConnectionState.Closed) myConnection.Dispose();
myConnection = null;
GC.Collect();
}
catch (Exception ex)
{
ExTrace.WriteLineIf(TraceLog.TraceError, ExTrace.ShowException(ex));
}
}
}
没有抛出异常,连接状态 == 已关闭,myConnection == null,但是 .ldb 文件从未消失。我的后续代码应该将 "myDatabase.mdb" 文件移动到 "myDatabase.bak",但由于文件已被我的程序使用,所以失败了。
我应该如何确保它实际上已关闭并且没有被锁定。
编辑:我根据下面评论的建议修改了代码,现在它可以工作了。
myConnection.Dispose();
显式调用GC.Collect()是让它正常工作的关键。
感谢您的帮助!