`pg`を使ったRubyからDBのデータを呼び出す手順

Sinatrapgを使ったメモアプリを作る課題があったので、備忘録としてpgを使ったDB操作をメモしておく。

pgって何?

github.com

Pg is the Ruby interface to the PostgreSQL RDBMS.

RubyでPostgresSQLとかのRDBMSを使うためのインターフェーストノコト

手順

  1. 適当なDBをPostgreSQLで使っておく
  2. gem install pg
  3. 適当なRubyファイルを作ってスクリプトを書き込む
#!/usr/bin/env ruby

require 'pg'

# Output a table of current connections to the DB
conn = PG.connect( dbname: 'template1' )
conn.exec( "SELECT * FROM Staff" ) do |result|
  result.each do |row|
    puts "番号:#{row["id"]} 名前: #{row["name"]} 年齢:#{row["age"]}"
  end
end
% ruby try_pg.rb
番号:001  名前: 雨宮蓮 年齢:17
番号:002  名前: 坂本竜司 年齢:17

PG.connect( dbname: 'database_name' ).execSQL文をかけばDBの操作をしてくれるので、putpostdeleteなどSinatraのルーティングに合わせて書く。

例)メモの作成

class Note
  class << self
    def create(title: note_title, body: note_body)
      connection = PG.connect( dbname: 'note_app' )
      connection.exec( "INSERT INTO note(title, body) VALUES ('#{title}', '#{body}')" )
    end
  end
end

post '/new' do
  Note.create(title: params[:title], body: params[:body])

  redirect to('/')
end

つくったメモアプリがこちら

f:id:ksmxxxxxx:20201229233823g:plain
メモアプリ