BLOGTIMES
::
Home > SQLiteをインメモリで使う
2010/01/18
[ by hsur at 18:44]

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が必要です→http://blog.cles.jp/item/3380
Trackbacks
このエントリにトラックバックはありません
Comments
愛のあるツッコミをお気軽にどうぞ。[policy]
古いエントリについてはコメント制御しているため、即時に反映されないことがあります。
コメントはありません
Comments Form

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

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

Web Services by Yahoo! JAPANPowered by NP_SpamBayesJP
★下記に2つの英単語をスペースで区切って入力してください
::
Home > SQLiteをインメモリで使う