Ruby リモートのデータベースにアクセス postgresql
sqlite3は、ローカル上にあるデータベースにしかできない。
ubuntu18.04上にある、postgresqlに,Macからアクセス
ruby-pgライブラリを使えば接続できる
postgresql用のgemをインストール
$ gem install pg -v '0.18.4' Fetching: pg-0.18.4.gem (100%) Building native extensions. This could take a while... ERROR: Error installing pg: ERROR: Failed to build gem native extension. ...
次のコマンドで postgresql をインストールすることで解決。
$ brew install postgresql
postgresqlにアクセスするには、libpgのCライブラリ
libpq - C ライブラリ
www.postgresql.jp › document › html › libpq
libpqは、 C 言語によるアプリケーションプログラマ用のPostgreSQLインタフェースです。 libpqは、クライアントプログラムからPostgreSQLのバックエンドサーバに問い合わせを渡し、その結果を受け取るためのライブラリ関数の集合です。
データベースに接続するためにPGのクラスメソッドconnectに引数を与える。connectメソッドの引数と意味は以下の通り。
https://deveiate.org/code/pg/PG/Connection.html 参照
connect(pghost, pgport, pgoptions, pgtty, dbname, login, passwd)
- pghost サーバのホスト名(文字列)
- pgport サーバがlistenしているポート番号(整数)
- pgoptions backendを起動する際に使用するオプション(文字列)
- pgtty backendがデバッグメッセージを表示するtty(文字列)
- dbname 接続するデータベース名(文字列)
- login ユーザ名(文字列)
- passwd パスワード(文字列)
失敗した場合は 例外が発生。
PG.connect('localhost',5432,'','','test_db','ri4u','')
このように適宜、省略も可能。
メソッドexecでクエリを実行。
q = "select * from hoge_table" res = conn.exec(q)
exec(sql)
sqlで指定されたSQL問い合わせ文をPostgreSQLへ送ります。問い合わせが成功した場合には、結果がPGresultクラスのインスタンスとして返され、そうでない場合は例外が発生します。
PG: The Ruby PostgreSQL Driver
https://deveiate.org/code/pg/PG/Connection.html
Superclass
rb_cObject
Included Modules
PG::Constants
https://deveiate.org/code/pg/PG/Constants.html
PostgreSQL接続クラスです。このクラスのインタフェースは、CアプリケーションプログラマのPostgreSQLへのインタフェースであるlibpqに基づいています。libpqにある程度精通していることが推奨されますが、必須ではありません。
# require "rubygems" require "pg" begin conn = PG.connect('192.168.0.100',5432,'','','matsuok','pgadmin','pppppp') q = "select * from personalinf where hometown = '岐阜県' and blood = 'AB'" res = conn.exec(q) res.each_with_index do |r, i| p i,r end rescue PG::Error => ex # PGError process print(ex.class," -> ",ex.message) rescue => ex # Other Error process print(ex.class," -> ",ex.message) ensure conn.close if conn end # row : {"serialno"=>"4435", "fullname"=>"大川梓", "namekatakana"=>"オオカワアズサ", "gender"=>"女", "phone"=>"0745201337", "email"=>"azusa996@nlolgtf.onz", "postalcode"=>"635-0804", "homeaddress1"=>"奈良県", "homeaddress2"=>"北葛城郡広陵町", "homeaddress3"=>"沢", "homeaddress4"=>"4-14", "homeaddress5"=>nil, "birth"=>"1986-05-21", "age"=>"33", "hometown"=>"岐阜県", "blood"=>"AB", "passw"=>"II87Syfe"}