RubyからのDB接続について調べてみる
Flickrへの画像アップロードが成功したので、今度はメタデータをDBから取り出すことにします。
メタデータはPostgreSQLに格納しているので、まずはRubyからPostgreSQLに接続するためにどんな方法があるかを調べてみると、ruby-postgresとpostgres-prというのがあるらしい。postgres-prはpure Rubyということなのだが、機能的にいろいろ制限がありそうなのでruby-postgresを使うことにします。奥の手としてはJRubyでJDBCを使うというのもあるけれど、今回はやめておきます。
ruby-postgres http://ruby.scripting.ca/postgres/
require 'rubygems' require 'postgres' conn = PGconn.open('dbname' => 'postgres', 'user' => 'postgres', 'password' => 'postgres') conn.set_client_encoding('SJIS') conn.query("SELECT user_id, user_account FROM user_data").each do |row| puts "#{row[0]} #{row[1]}" end
うーん、row[0]とか美しくないな。