7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

mysql2-cs-bind + sql-maker で、MySQLを操作するスクリプトを書く

Posted at

概要

おもむろにテキストエディタを開いて、
DBを操作するスクリプトを書きたい時がある。
O/Rマッパを導入するのも面倒くさいし、
SQLをガリガリ書きたいし、
でもINSERT/UPDATEなどの簡単なSQLを手書きしたくない。

mysql2-cs-bind と sql-maker で快適にスクリプトが書けるようになる。

mysql2-cs-bind は、mysql2 にはない prepare statement を擬似的に行うメソッドを用意してくれている。
sql-makerのみ使うなら、:auto_bindオプションで済むので、このモジュールは要らないが、直接SQLを書く場合は、エスケープしてSQLに組み込むということを自動で行ってくれるので便利。

sql-makerは、ハッシュや配列のデータ構造からSQL文字列を生成してくれるモジュール。INSERT/UPDATE/DELETE と 単純なSELECTは、このモジュールで生成したほうが楽。

インストール

mysql2-cs-bind と sql-maker をインストールするためGemfileを作成する。

shell
$ bundle init
$ vim Gemfile
Gemfile
# A sample Gemfile
source "https://rubygems.org"

gem 'sql-maker'
gem 'mysql2-cs-bind'

インストールする。

shell
$ bundle install

スクリプトを書く

以下のような感じで、スクリプトを書くことができる。

sample.rb
require 'sql-maker'
require 'mysql2-cs-bind'

DB_HOST = 'localhost'
DB_USER = 'root'
DB_PASS = ''
DB_NAME = 'hogehoge'



builder = SQL::Maker.new(:driver => 'mysql')
dbh = Mysql2::Client.new(
    :host => DB_HOST,
    :username => DB_USER,
    :password => DB_PASS,
    :database => DB_NAME
)

# SELECT
sql, binds = builder.select('users', ['*'], {:id => 1})
dbh.xquery(sql, binds).each do |row|
   p row
end

# INSERT
sql, binds = builder.insert('users', {:name => 'hanako'})
dbh.xquery(sql, binds)

# UPDATE
sql, binds = builder.update('users', {:name => 'tarou'}, {:id => 1})
dbh.xquery(sql, binds)

# DELETE
sql, binds = builder.delete('users', {:id => 1})
dbh.xquery(sql, binds)

実行

shell
$ bundle exec -- ruby sample.rb

参考

mysql2-cs-bind released!
http://d.hatena.ne.jp/tagomoris/20120420/1334911716

perl の SQL::Maker (と SQL::QueryMaker) を ruby に移植した
http://blog.livedoor.jp/sonots/archives/38723820.html

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?