MySqlを使ってみるselect,insert

@pagesでは、rubyとMySqlを使えると聞いて手を出してみたので、MySqlの使い方を調べてみました。


サンプルダウンロード


MySqlに接続

@pagesでMySqlに接続するには、ユーザー名、パスワード、ホスト名、データベース名を管理画面から取得し、
以下のようにMysql::newに設定します。
# DB接続
require 'mysql'
 
user = 'ユーザー名'
pass = 'パスワード'
host = 'localhost'
name = 'データベース名'
 
db = Mysql::new(host, user, pass, name )
 

select文の実行

パラメータのないselect文なら、queryメソッドでselect文を実行し、Mysql::Resultオブジェクトを取得できます。
# クエリ実行
res = db.query("select * from TestTable")
 

select文の実行結果取得

select文の実行結果は、eachメソッドでカラムの配列として取得できます。
# データ取得&出力
res.each do |row|
  col1 = row[0]
  col2 = row[1]
  col3 = row[2]
  col4 = row[3]
end
 

insert文の実行

insert文はパラメータが基本必要なので、Mysql#prepareメソッドを使い、Mysql::Stmtオブジェクトを取得します。
Mysql::Stmt#executeメソッドにパラメータを渡すと、クエリの ? にパラメータが設定されます。
select文のパラメータを設定する場合も、同じ方法でよいと思います。
# クエリ実行
st = db.prepare("insert into TestTable (name, birth, address, email) values (?,?,?,?)")
st.execute(name, birth, address, email)
st.close()
db.close()
 

リクエストパラメータの取得

フォームから送信されたリクエストパラメータの取得はCGI#paramsメソッドを使いHashを取得します。
# リクエストパラメータ取得
require 'cgi'
cgi = CGI.new
name = cgi["name"]
birth = cgi["birth"]
address = cgi["address"]
email = cgi["email"]
 

リダイレクト

insert後はまた初期画面に戻りたいので、Ggi#headerメソッドを使い標準出力に結果を出力します。
# mysql.cgiへリダイレクト
print cgi.header({'status' => '302 Found', 'Location' => 'mysql.cgi' })
 

サンプルソース(mysql.cgi)

「TestTable」のデータを全て読み込んで画面に表示し、新しいデータの入力フォームを表示します。
入力フォームはmysql.insert.cgiに送信します。
#!/usr/local/bin/ruby
 
# コンテンツタイプ出力
print "Content-type: text/html\n\n"
 
# ヘッダ出力
print(<<"head")
<html>
  <head>
    <title>ruby and MySql - ちゃぱてぃ商店@pages</title>
    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">
  </head>
head
 
# DB接続
require 'mysql'
 
user = 'chapati'
pass = 'ぱすわーど'
host = 'localhost'
name = 'db0chapati'
 
db = Mysql::new(host, user, pass, name ) 
 
# クエリ実行
res = db.query("select * from TestTable")
 
# データ取得&出力
res.each do |row|
  col1 = row[0]
  col2 = row[1]
  col3 = row[2]
  col4 = row[3]
 
  puts col1
  puts ", "
  puts col2
  puts ", "
  puts col3
  puts ", "
  puts col4
  puts "<br>"
end
 
db.close()
 
# フォーム出力
print(<<"form")
<form action='mysql.insert.cgi'>
  <label>名前:</label>
  <input type='text' id='name' name='name' /><br>
 
  <label>生年月日:</label>
  <input type='text' id='birth' name='birth' /><br>
 
  <label>住所:</label>
  <input type='text' id='address' name='address' /><br>
 
  <label>メールアドレス:</label>
  <input type='text' id='email' name='email' /><br>
 
  <input type='submit'>
</form>
form
 
print "</html>"

サンプルソース(mysql.insert.cgi)

mysql.cgiからリクエストパラメータを受け取り、「TestTable」に新しいレコードを作成するサンプルです。
新しいレコードの作成後は「mysql.cgi」にリダイレクトします。
#!/usr/local/bin/ruby
 
# リクエストパラメータ取得
require 'cgi'
cgi = CGI.new
name = cgi["name"]
birth = cgi["birth"]
address = cgi["address"]
email = cgi["email"]
 
# DB接続
require 'mysql'
user = 'ユーザー名'
pass = 'ぱすわーど'
host = 'localhost'
dbname = 'db0chapati'
 
db = Mysql::new(host, user, pass, dbname ) 
 
# クエリ実行
st = db.prepare("insert into TestTable (name, birth, address, email) values (?,?,?,?)")
st.execute(name, birth, address, email)
st.close()
db.close()
 
# mysql.cgiへリダイレクト
print cgi.header({'status' => '302 Found', 'Location' => 'mysql.cgi' })
 
 

タグ:

ruby @pages mysql
最終更新:2012年11月05日 03:04
添付ファイル