pgでSQLを実行するいくつかの方法
パターン1:PG::Connection#execを使う方法
code:exec.rb
require 'pg'
conn = PG::Connection.open(:dbname => 'test')
res = conn.exec('SELECT 1, 2, NULL')
パターン2:PG::Connection#exec_paramsを使う方法
code:exec_params.rb
require 'pg'
conn = PG::Connection.open(:dbname => 'test')
res = conn.exec_params('SELECT $1, $2, $3', 1, 2, nil) # 次のように評価される:
# res = conn.exec('SELECT 1, 2, NULL')
PQexecParams
パターン3:PG::Connection#prepareとPG::Connection#exec_preparedを使う方法
code:exec_prepared.rb
require 'pg'
conn = PG::Connection.open(:dbname => 'test')
# 例えば stmt という名前で、ステートメントを準備する
conn.prepare('stmt','SELECT $1, $2, $3')
# ステートメントにパラメータを渡して実行する
# 次のように評価される:
# res = conn.exec('SELECT 1, 2, NULL')
PQprepare
PQexecPrepared
This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed.
同じSQL文を繰り返し利用する場合は、exec_paramsで都度SQL文を渡すのではなく、exec_preparedで準備したステートメントを使うと効率が良い
exec_paramやexec_preparedを使う(静的プレースホルダーを利用する)場合は、エスケープ処理は不要。
静的プレースホルダーを使わずexecで実行する(動的プレースホルダーを利用する?)場合は、エスケープ処理が必要。
参考URL