Last active
February 20, 2018 07:40
-
-
Save thinkAmi/34cdc817f99d27a11d13 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' | |
def write(msg) | |
puts "\n" | |
puts '-' * 20 | |
puts msg | |
puts '-' * 20 | |
end | |
# CP932とUTF-8のシンボルのテスト | |
write('シンボルのテスト') | |
## 日本語シンボル(cp932) | |
key = '名前'.force_encoding('cp932').to_sym | |
p key.encoding #=> <Encoding:Windows-31J> | |
p Symbol.all_symbols.select{|e| e == key}.count #=> `1`となり、登録されている | |
## 日本語シンボル(UTF-8) | |
p :名前.encoding #=> #<Encoding:UTF-8> | |
p Symbol.all_symbols.select{|e| e == :名前}.count #=> `1`となり、登録されている | |
h = { key => 'hoge' } | |
p h[key] #=> "hoge" | |
p h[:名前] #=> nil | |
j = { :名前 => 'fuga' } | |
p j[key] #=> nil | |
p j[:名前] #=> "fuga" | |
# 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}") | |
## エイリアスを使わないで取得してみる | |
write('エイリアスなし') | |
ds1 = db[:日本語サンプル].select(:名前, :コメント).where(ID: :$n) | |
r1 = ds1.prepare(:first).call(n: 1) | |
### 取得できたかを確認: 取得できている | |
p r1 #=> {:名前=>"ほげ", :コメント=>"ホゲ"} | |
### 事前に用意したシンボルで、特定の列を取得してみる | |
p r1[key] #=> nil (CP932のシンボルで列を取得できない) | |
p r1[:名前] #=> nil (UTF-8のシンボルで列を取得できない) | |
### カラム名のエンコーディングを取得してみる | |
r1.each do |k, v| | |
p k #=> `:名前` or `:コメント` | |
p k.encoding #=> #<Encoding:Windows-31J> | |
end | |
## エイリアスを使って取得してみる | |
write('エイリアスあり') | |
ds2 = db[:日本語サンプル].select(:名前___name, :コメント___comment).where(ID: :$n) | |
r2 = ds2.prepare(:first).call(n: 1) | |
### 取得できたかを確認: 取得できている | |
p r2 #=> {:name=>"ほげ", :comment=>"ホゲ"} | |
# エイリアスで、特定の列を取得してみる | |
p r2[:name] #=> "ほげ" | |
p r2[:comment] #=> "ホゲ" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment