LoginSignup
10
8

More than 5 years have passed since last update.

pythonのsqlite3でインメモリDBをセーブ/ロードする

Posted at

sqlite3.connect(':memory:') として
メモリ上に作成されたDBイメージは、
ダンプファイルにすることで保存できます。

以下のサンプルではダンプファイルはgzipで格納してます。

#ファイルからロード
con = sqlite3.connect(':memory:')
fp = gzip.open('./dump.sql.gz' ,'rb')
con.executescript(fp.read())
fp.close()

#ファイルへセーブ
fp = gzip.open('./dump.sql.gz','wb')
for line in con.iterdump():
  fp.write('%s\n' % line)
fp.close()

ただし、この方法では件数が増えると、
ロードにとても時間がかかるため実用的ではありません。

実用上ではsqlite3.connect(':memory:')を使わず
tmpfsにdbファイルを置いたほうがいいです。

10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8