#!/usr/bin/ruby
require "rubygems"
require "pg"
$hostname = "localhost"
$port = 5432
$dbname = "データベース名"
$username = "ユーザ名"
$password = "パスワード"
$encode = "UTF-8"
$tbl = "テーブル名"
print "Content-type: text/html\n\n";
print "
CGI-Ruby usePg TEST\n";
print "\n";
print "DB接続テスト(CGI-Ruby rubygems版)
\n";
conn = PGconn.connect($hostname, $port, "", "", $dbname, $username, $password)
conn.set_client_encoding($encode)
##### データ挿入メソッド
def insert(conn)
$sql1 = "insert into " + $tbl + " values('data1','data2','data3');"
res = conn.exec($sql1)
end
##### データ更新メソッド
def update(conn)
$sql2 = "update " + $tbl + " set name='new_data' where name='old_data';"
res = conn.exec($sql2)
end
##### データ削除メソッド
def delete(conn)
$sql3 = "delete from " + $tbl + " where name='data';"
res = conn.exec($sql3)
end
##### データ表示メソッド
def view(conn)
$sql = "select * from " + $tbl + ";"
res = conn.exec($sql)
rows = res.num_tuples
cols = res.num_fields
for i in 0..rows-1 do
for j in 0..cols-1 do
print res.getvalue(i,j)," "
end
print "
\n"
end
end
begin
##### データ挿入
# insert(conn)
##### データの更新
# update(conn)
##### データの削除
# delete(conn)
##### データ表示
view(conn)
rescue => ex
conn.exec("ROLLBACK;")
print ex.message, "
\n"
ensure
conn.close()
end
print "\n";