System.data.sqlite - 激活WAL日志模式

7
我正在我的vb.net程序中使用System.data.sqlite.dll。我无法找出激活WAL模式的代码。

我是在创建数据库后立即激活此命令还是每次使用新的SQLiteConnection时激活它?

如果是这样,现在需要使用什么代码,我正在使用类似以下的代码:

cnn As New SQLiteConnection(String.Format("Data Source={0}\{1};PRAGMA jounal_mode=WAL;", Application.StartupPath, DBName))

这是 PRAGMA 命令的正确使用方式吗?

3个回答

9

您可以始终使用 SQLiteConnectionStringBuilder 类来执行此操作:

    SQLiteConnectionStringBuilder connBuilder = new SQLiteConnectionStringBuilder();
    connBuilder.DataSource = filePath;
    connBuilder.Version = 3;
    //Set page size to NTFS cluster size = 4096 bytes
    connBuilder.PageSize = 4096;
    connBuilder.CacheSize = 10000;
    connBuilder.JournalMode = SQLiteJournalModeEnum.Wal;
    connBuilder.Pooling = true;
    connBuilder.LegacyFormat = false;
    connBuilder.DefaultTimeout = 500;
    connBuilder.Password = "yourpass";


    using(SQLiteConnection conn = new SQLiteConnection(connBuilder.ToString()))
    {
    //Database stuff
    }

请注意,您不必为每个连接设置WAL - 只需在创建数据库时设置一次即可。 - Przemysław Michalski

4
这是我项目中的示例连接字符串(App.config):

  <connectionStrings>
    <add name="SQLiteDb" providerName="System.Data.SQLite" connectionString="Data Source=data.sqlite;Version=3;Pooling=True;Synchronous=Off;journal mode=Memory"/>
  </connectionStrings>

您可以将journal mode=Memory更改为journal mode=WAL

如果您没有在连接字符串中指定日志模式,您可以通过执行PRAGMA jounal_mode=WAL查询来手动切换数据库的日志模式。


1

你需要将pragma作为一个非查询命令来执行。

Using cmd As SQLiteCommand = cnn.CreateCommand()
   cmd.CommandText = "PRAGMA journal_mode=WAL"
   cmd.ExecuteNonQuery()
End Using

只要您保持连接开启,设置一次就足够了。

1
谢谢,非常感谢。然而,我倾向于经常关闭连接,通常是在插入、更新等操作之后。这是否意味着我必须将它与我的插入、更新、删除函数一起包含? - Mike Rebosse
2
很遗憾,是的。如果它是一个仅限本地的数据库,那么在应用程序的整个生命周期中保持连接打开不应该有任何缺点。我们经常在具有本地DB的移动和平板设备上这样做。 - competent_tech

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接