sqlite - 删除sqlite db文件

标签 sqlite c#-4.0 sqlexception drop-database

我正在开发一个 C# 应用程序,其后端为 sqlite。在我的应用程序中,我有一个用于清理数据库的按钮(删除 .db 文件并使用一些初始数据再次创建它)。有时,当我尝试删除数据库时,它说无法删除它,因为它正在被另一个进程使用。在删除它之前,我使用了关闭连接、处理和清除池功能。即使那样,它也会抛出相同的异常。这是我的代码:

string targetDataBaseFilePath = Path.Combine(dataDirectoryPath, "local.db");               
ThingzDatabase.Create(targetDataBaseFilePath, "touchdb");

在创建函数中,我定义了以下代码,从那里我得到错误:
if (File.Exists(DatabaseFileName))
{
    try
    {
        ThingzDatabase.localdb.conn.Close();
        ThingzDatabase.localdb.conn.Dispose();
        SQLiteConnection.ClearAllPools();
    }
    catch (Exception)
    {
    }
    File.Delete(DatabaseFileName); //error throws from here.                       
}

如何防止错误被抛出?

最佳答案

FileInfo fi = new FileInfo(DatabasePath);
try
{
    if (fi.Exists)
    {
        SQLiteConnection connection = new SQLiteConnection("Data Source=" + DatabasePath + ";");
        connection.Close();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        fi.Delete();
    }
}
catch(Exception ex)
{
    fi.Delete();
}
数据库路径 是你的数据库文件路径

关于sqlite - 删除sqlite db文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6384207/

相关文章:

python - 自动创建用于测试的数据库

visual-studio-2010 - C# 4 中 MemoryMappedFile 上的 UnauthorizedAccessException

c# - 用于查询事件网络和关联连接的 WMI

java - SQLException(无效的列索引) - 页面中没有显示结果

java - 如何从java向数据库添加日期

sqlite - 在关闭应用程序之前,为什么我的SQLite数据库不添加数据?

sqlite - Codeception - 由于配置无效,无法使用 DB 模块

database - 需要帮助插入数据库

c# - Crystal 报表在 Visual Studio 2010 中不工作

java.sql.SQLFeatureNotSupportedException 在 org.sqlite.jdbc4.JDBC4PreparedStatement.setBinaryStream(JDBC4PreparedStatement.java :96)