pgを使用したPostgresqlへのアクセス

pg を用いてPostresqlへアクセスする課題があったので備忘録として。

pgとは

PostgreSQLリレーショナルデータベースにアクセスするためのライブラリである。
君の瞳はまるでルビー - Ruby 関連まとめサイト

手順

  1. pgをインストール
    Gemfilepgを追加して$ bundle install

    # Gemfile
    # frozen_string_literal: true
    source 'https://rubygems.org'
    gem 'sinatra'
    gem 'sinatra-contrib'
    gem 'pg'
    # ruby 3.0.0以降を使用するため下記gemを追加
    gem 'webrick'
    
    $ bundle install
    Calling `DidYouMean::SPELL_CHECKERS.merge!(error_name => spell_checker)' has been deprecated. Please call `DidYouMean.correct_error(error_name, spell_checker)' instead.
    Fetching gem metadata from https://rubygems.org/.........
    Resolving dependencies...
    Using bundler 2.1.4
    Using multi_json 1.15.0
    Using ruby2_keywords 0.0.5
    Using mustermann 1.1.1
    Fetching pg 1.3.5
    Installing pg 1.3.5 with native extensions
    Using rack 2.2.3
    Using rack-protection 2.2.0
    Using tilt 2.0.10
    Using sinatra 2.2.0
    Using sinatra-contrib 2.2.0
    Using webrick 1.7.0
    Bundle complete! 4 Gemfile dependencies, 11 gems now installed.
    Use `bundle info [gemname]` to see where a bundled gem is installed.
    
  2. Postgresqlに接続
    どうやらconnectする際の引数は省略することができるみたい🤔

    # db_test.rb
    # frozen_string_literal: true
    require 'pg'
    connect = PG::connect(host: "localhost", user: "choco", password: "", dbname: "postgres", port: "")
    results = connect.exec("select * from hoge")
    results.each { |result| p result }
    connect.finish
    
    #実行結果
    $ ruby db_test.rb
    {"id"=>"1", "name"=>"hoge"}
    {"id"=>"2", "name"=>"hogehoge"}