BLOGTIMES
2010/01/18

SQLiteをインメモリで使う

  ruby  sqlite 
このエントリーをはてなブックマークに追加

SQLiteはデータのちょっとした加工や管理に便利なので、最近よく使っているのですが、ファイルの指定を:memory:とすると、インメモリで使うことができるという機能をみつけたので、Rubyからちょっと使ってみました。

In-Memory Databases

For example:
rc = sqlite3_open(":memory:", &db);

When this is done, no disk file is opened. Instead, a new database is created purely in memory. The database ceases to exist as soon as the database connection is closed. Every :memory: database is distinct from every other. So, opening two database connections each with the filename ":memory:" will create two independent in-memory databases.

利用例

#!/usr/bin/ruby require 'rubygems' require 'sqlite3' db = SQLite3::Database.new(':memory:') db.execute(<<EOS) CREATE TABLE test ( id varchar(255), PRIMARY KEY(id) ) EOS stmt = db.prepare(<<EOS) INSERT INTO test(id) VALUES(:id) EOS stmt.execute( :id => "a" ) stmt.execute( :id => "b" ) stmt.execute( :id => "c" ) stmt.execute( :id => "d" ) stmt.close count = db.get_first_value("SELECT count(*) FROM test") puts "count(*): #{count}" db.execute('select * from test') do |row| puts row.join("\t") + "\n" end db.close

ファイルに書き出されないという部分以外は普通にSQLiteですね。
上記スクリプトの実行結果は下記のようになります。

count(*): 4 a b c d

    トラックバックについて
    Trackback URL:
    お気軽にどうぞ。トラックバック前にポリシーをお読みください。[policy]
    このエントリへのTrackbackにはこのURLが必要です→https://blog.cles.jp/item/3380
    Trackbacks
    このエントリにトラックバックはありません
    Comments
    愛のあるツッコミをお気軽にどうぞ。[policy]
    古いエントリについてはコメント制御しているため、即時に反映されないことがあります。
    コメントはありません
    Comments Form

    コメントは承認後の表示となります。
    OpenIDでログインすると、即時に公開されます。

    OpenID を使ってログインすることができます。

    Identity URL: Yahoo! JAPAN IDでログイン