在Microsoft.Data.Sqlite的某些情况下,使用Mode=ReadWriteCreate不会创建数据库

pkmbmrz7  于 2022-12-13  发布在  SQLite
关注(0)|答案(1)|浏览(164)

目前,我正在尝试完全删除一个Sqlite数据库,如果检测到数据库损坏,则重新创建它。
然而,当我:
1.使用Mode=ReadWriteCreate创建数据库
1.删除
1.与步骤1相同,再次重新创建
不会重新创建数据库文件。更具体地说,下面的代码:

using System;
using System.IO;
using Microsoft.Data.Sqlite;

namespace PotentialSqliteBug
{
    class Program
    {
        private static string DbPath = "/Users/jbickle/Downloads/SomeDatabase.sqlite";
        private static string ConnectionString = $"Data Source={DbPath};Mode=ReadWriteCreate";
            
        static void Main(string[] args)
        {
            using var connection = new SqliteConnection(ConnectionString);
            connection.Open();

            if (File.Exists(DbPath))
                Console.WriteLine("The database exists after connection was opened.");
            else
            {
                Console.WriteLine("The database DOES NOT exist after connection was opened.");
                return;
            }

            connection.Close();
            
            File.Delete(DbPath);
            if (File.Exists(DbPath))
                Console.WriteLine("The database unexpectedly exists after attempting to delete it.");
            else
                Console.WriteLine("The database no longer exists after attempting to delete it, as expected.");
            
            using var secondConnection = new SqliteConnection(ConnectionString);
            secondConnection.Open();

            if (File.Exists(DbPath))
                Console.WriteLine("The database exists after connection was opened.");
            else
                Console.WriteLine("The database DOES NOT exist after connection was opened.");
        }
    }
}

产生下列输出:

The database exists after connection was opened.
The database no longer exists after attempting to delete it, as expected.
The database DOES NOT exist after connection was opened.

这是一个问题,因为尝试执行查询或创建事务会导致Sqlite错误26:“文件不是数据库”。
所以我的问题是:我是不是误解了在Microsoft.Data.Sqlite中创建数据库的工作原理?我怎样才能重新创建一个损坏的Sqlite数据库而不产生这样的副作用呢?
还有一点困惑:如果我删除connection.Close()行,数据库 * 不会 * 按预期重新创建。显然,这不是一个很好的解决方案,因为永远挂起数据库连接并不理想。
如果这很重要,请在macOS 12.3.1上的.NET 6.0.402 SDK中执行此代码

qnzebej0

qnzebej01#

它可能与第一个连接保持在作用域中有关,即使您关闭了它。您可以尝试使用connection.Dispose()显式处理它,或者将它 Package 在using语句中:

using (var connection = new SqliteConnection(ConnectionString))
{
    connection.Open();

    if (File.Exists(DbPath))
        Console.WriteLine("The database exists after connection was opened.");
    else
    {
        Console.WriteLine("The database DOES NOT exist after connection was opened.");
        return;
    }
}

相关问题