Created
July 4, 2014 19:52
-
-
Save thinkAmi/a4c7c73df1cf8cf49175 to your computer and use it in GitHub Desktop.
Ruby + Sequelを使って、MS Accessの選択クエリからデータを取得する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sequel' | |
# MS Accessの選択クエリ(AccdbQuery)のSQLビュー | |
# SELECT ID, 名前 AS Name, [コメント] AS Comment | |
# FROM 日本語サンプル; | |
def write(msg) | |
puts "\n" | |
puts '-' * 20 | |
puts msg | |
puts '-' * 20 | |
end | |
# Sequel + ADO による MS Accessへの接続 | |
ACCDB_PATH = '//127.0.0.1/db/Sample.accdb' | |
OLEDB_PROVIDER = 'Microsoft.ACE.OLEDB.12.0' | |
ODBC_DRIVER = '{Microsoft Access Driver (*.mdb, *.accdb)}' | |
db = Sequel.ado(conn_string: "Provider=#{OLEDB_PROVIDER};Data Source=#{ACCDB_PATH}") | |
ds = db[:AccdbQuery] | |
# SELECT | |
write('SELECT') | |
r = ds.select(:Name, :Comment).where(ID: :$n).prepare(:first).call(n: 1) | |
p r #=> {:Name=>"ほげ", :Comment=>"ホゲ"} | |
p r[:Name] #=> "ほげ" | |
p r[:Comment] #=> "ホゲ" | |
p ds.all | |
#=> [{:ID=>1, :Name=>"ほげ", :Comment=>"ホゲ"}, {:ID=>2, :Name=>"ふが", :Comment=>"フガ"}] | |
# @@IDENTITYの動作を確認するため、一度データを投入・削除しておく | |
write('INSERT - Preparation') | |
2.times { |i| ds.insert(Name: i.to_s) } | |
p ds.all | |
#=> [{:ID=>1, :Name=>"ほげ", :Comment=>"ホゲ"}, {:ID=>2, :Name=>"ふが", :Comment=>"フガ"}, {:ID=>3, :Name=>"0", :Comment=>nil}, {:ID=>4, :Name=>"1", :Comment=>nil}] | |
ds.where{id > 2}.delete | |
# ds.where(Sequel.expr(:ID) > 2).delete # これでもOK | |
p ds.all | |
#=> [{:ID=>1, :Name=>"ほげ", :Comment=>"ホゲ"}, {:ID=>2, :Name=>"ふが", :Comment=>"フガ"}] | |
# INSERT | |
ds.insert(Name: 'Piyo', Comment: 'insert') | |
# @@IDENTITYを使って、INSERT時に採番されたオートナンバー型のID列を取得する | |
id = db['SELECT @@IDENTITY as ID From AccdbQuery'].first[:ID] | |
puts "\n@@IDENTITY: #{id}" #=> @@IDENTITY: 5 | |
write('INSERT') | |
p ds.all | |
#=> [{:ID=>1, :Name=>"ほげ", :Comment=>"ホゲ"}, {:ID=>2, :Name=>"ふが", :Comment=>"フガ"}, {:ID=>5, :Name=>"Piyo", :Comment=>"insert"}] | |
# UPDATE | |
ds.where(ID: id).update(Name: 'ぴよ', Comment: 'Update') | |
write('UPDATE') | |
p ds.all | |
#=> [{:ID=>1, :Name=>"ほげ", :Comment=>"ホゲ"}, {:ID=>2, :Name=>"ふが", :Comment=>"フガ"}, {:ID=>5, :Name=>"ぴよ", :Comment=>"Update"}] | |
# DELETE | |
ds.where(ID: id).delete | |
write('DELETE') | |
p ds.all | |
#=> [{:ID=>1, :Name=>"ほげ", :Comment=>"ホゲ"}, {:ID=>2, :Name=>"ふが", :Comment=>"フガ"}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment