如何在WAL模式下打开SQLite连接

Nic*_*oul 11 c# sqlite wal

在C#中,如何在WAL模式下打开SQLite连接?

以下是我在正常模式下打开的方式:

SQLiteConnection connection = new SQLiteConnection("Data Source=" + file);
connection.Open();
// (Perform my query)
Run Code Online (Sandbox Code Playgroud)

Tur*_*bot 13

如何在SQLiteConnection连接字符串中指定工厂方法?

例如

public static class Connection
{
    public abstract SQLiteConnection NewConnection(String file);
}

public class NormalConnection : Connection 
{
  public override SQLiteConnection NewConnection(String file)
  {
     return new SQLiteConnection("Data Source=" + file);
  }
}

public class WALConnection : Connection 
{
  public override SQLiteConnection NewConnection(String file)
  {
    return new SQLiteConnection("Data Source=" + file + ";PRAGMA journal_mode=WAL;"
  }
}
Run Code Online (Sandbox Code Playgroud)

代码没有经过测试,但我希望你能得到这个想法,所以当你使用它时,你可以这样做.

   SQLiteConnection conWal = new WALConnection(file);
    conWAL.Open();

    SQLiteConnection conNormal = new NormalConnection(file);
    conNormal.Open();
Run Code Online (Sandbox Code Playgroud)

  • 考虑到SQLite连接字符串中允许的参数数量,您的方法是组合学中一个有趣的案例研究:) (2认同)

Nic*_*oul 10

以下这一行是我所寻找的,非常感谢Turbot的回答包括:

new SQLiteConnection("Data Source=" + file + ";PRAGMA journal_mode=WAL;")
Run Code Online (Sandbox Code Playgroud)

  • 使用此方法会在 Microsoft.Data.Sqlite 库中引发 ArgumentException。对于那些使用这个库的人来说,打开连接后立即使用 SqliteCommand 执行 PRAGMA 是正确的方法。(就像你的“不太完美”的解决方案一样。) (2认同)

Nic*_*oul 7

这是我不太完美的解决方案:

SQLiteConnection connection = new SQLiteConnection("Data Source=" + file);
connection.Open();
using (var command = new SQLiteCommand(sqliteConnection))
{
    command.CommandText = "PRAGMA journal_mode=WAL";
    command.ExecuteNonQuery();
}
// (Perform my query)
Run Code Online (Sandbox Code Playgroud)

如果您知道一些不那么冗长的信息,我会很高兴听到!

  • 我相信这是唯一正确的答案。上面的答案在连接字符串中设置 PRAGMA 对我来说不起作用。 (4认同)

Ale*_*tov 7

WAL模式的持久化

“与其他日志模式不同,PRAGMAjournal_mode=WAL 是持久的。如果进程设置 WAL 模式,然后关闭并重新打开数据库,数据库将返回 WAL 模式。”

http://www.sqlite.org/wal.html

如果我理解正确的话,这意味着您可以为数据库设置一次 WAL 模式,无需在每个连接上都设置它。

您可以使用 SQLite 的命令行 shell 来完成此操作: http://www.sqlite.org/sqlite.html