Sinatraとpg
を使ったメモアプリを作る課題があったので、備忘録としてpg
を使ったDB操作をメモしておく。
pgって何?
Pg is the Ruby interface to the PostgreSQL RDBMS.
RubyでPostgresSQLとかのRDBMSを使うためのインターフェーストノコト
手順
- 適当なDBをPostgreSQLで使っておく
gem install pg
- 適当な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' ).exec
でSQL文をかけばDBの操作をしてくれるので、put
やpost
、delete
など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