Help us understand the problem. What is going on with this article?

mysql2 gemのprepared statement機能メモ

More than 1 year has passed since last update.

rubyのmysql2にprepared statementがサポートされました。
使い方がどこにも書いてないのでメモしときます。

require 'mysql2'

client = Mysql2::Client.new(
  :host => "localhost",
  :username => "username",
  :password => "XXXXXXXXX",
  :database => "database"
)

sql = %{
  SELECT 
    id,
    created_date as created_at
  from users
  where 
    created_date > ?
    limit ?
}
stmt = client.prepare(sql)

# DateやTimeは自動的にCastされる
# パラメータが足りなければ当然エラー
res = stmt.execute(Date.today - 365, 100)
res.each { |c| p c }

# field名を取得
p stmt.fields

# close は GC 時に自動で呼ばれるが明示的に呼ぶこともできる
stmt.close

2018/09/22 sonots 追記:

mysql2 gem の prepared statement は server side prepared statement です。mysql の statement handle は使い回すのが正しい使い方なので、stmt オブジェクトをすぐに close して破棄するのではなく、キャッシュして使い回すのが正しい使い方となります。

mysql2 gem そのものに Go の Prepared Statement のような気の利いたキャッシュ機構はないですが、ActiveRecordではデフォルト1 connectionにつき1000 statementまでStatementPoolというところにキャッシュして超えたら一番古いやつを捨てるような実装になっているとのこと。

ref. https://twitter.com/sonots/status/1042829959989882880

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした