basyura's blog

あしたになったらほんきだす。

Ruby から sqlite3 を使う

正直 sqlite がどういうものか良く分かってなかった・・・。貧弱だけどお手頃な DB だろ程度にしか思ってなかったけど、すごいなこれ。面白い。

SQLite はMySQLやPostgreSQLと同じDBMS(データベース管理ソフト)であるが、サーバとしてではなくアプリケーションに組み込まれて利用される軽量データベースである。 一般的なRDBMSに比べて大規模な仕事には不向きだが、中小規模ならば速度も遜色はない。 また、APIは単純で単にライブラリを呼び出すだけであり、データの保存には単一のファイルしか使用しない事も特徴である。

SQLite - wikipedia

単一ファイルで移動させても OK とか面白すぎる。使い方も簡単だ。

DB作る

$ sqlite3 Tests.db
SQLite version 3.6.6.2
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table Users(id int, name text);
sqlite> .tables
Users

ruby から使う

require 'rubygems'
require 'sqlite3'

db = SQLite3::Database.new("Tests.db")
db.execute("insert into Users values(1,'basyura')")
db.execute("select * from Users").each{|id , name|
  puts id
  puts name
} 

Active Record から使う

require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
  :adapter => 'sqlite3',
  :dbfile  => 'Tests.db'
)

class User < ActiveRecord::Base ; end

User.find(:all).each{|r|
  puts r.id
  puts r.name
}