如何将内存中的sqlite数据库保存到perl中的文件中?

时间:2018-11-14 15:57:36

标签: sqlite perl

我使用以下方法创建一个SQLite database in memory

my $dsn      = "dbi:SQLite:dbname=:memory:"; # better in read/write operations performance than disk-file saved database.
my $user     = "";
my $password = "";
my $dbh = DBI->connect($dsn, $user, $password,{});

#… Doing some processing on the database (Creating tables/Inserting rows/Updating fields)

#… After finishing, I need to save the database to a local disk file.

我需要做的是在完成内存数据库的播放之后,我需要将其保存到磁盘文件file.db中。


已更新(答案汇总):
•有用的命令:
感谢Schwern的回答和comment

  • $dbh->sqlite_backup_to_file( $file_path ) 将数据库从内存复制到文件。
  • $dbh->sqlite_backup_from_file( $file_path ) 将数据库从文件复制到内存。
  • my $dbh = DBI->connect($dsn, $user, $password,{AutoCommit => 0}) 禁用AutoCommit似乎是一种更好和更简单的选项,可以像使用前两个命令一样优化性能。我只需要确保在关闭AutoCommit时,SQLite SELECT操作不会执行任何磁盘活动(other question)。
    • 更新: Performance testingSchwern(提到here)表明,对内存数据库或磁盘数据库进行操作和查询会得出相同的结果性能。

1 个答案:

答案 0 :(得分:5)

是的,您可以使用$dbh->sqlite_backup_to_file( $filename ),然后像普通的SQLite数据库一样连接到该文件。有关更多信息,请参见the SQLite Backup API docs

但是您可以通过turning off AutoCommit以相同的性能完成基本相同的事情,并且仅在完成大容量插入后才提交事务。 SQLite可能会在提交之前将所有插入内容保存在内存中。

my $dbh = DBI->connect(
    "dbi:SQLite:dbname=test.sqlite", undef, undef, { RaiseError => 1, AutoCommit => 0 }
);

...do your inserts...

$dbh->commit;

A simple benchmark显示出它既快又灵活。

关闭AutoCommit将使您无论选择哪种选项都有很大帮助。