詳細検索

Get the results of a MySQL query in bare Ruby

Avatar
by maeno
2 min read

Get the results of a MySQL query in bare Ruby
Translated from 日本語 • View original

When processing Ruby + MySQL, I think there are many cases where 'ruby-mysql' or 'mysql2' is used in the MySQL operation system libraries, but since it was necessary to perform MySQL query operations in a raw Ruby environment without these libraries, I tried to generalize the source I wrote at that time and summarize it. Well... There may be almost no need, but I thought I'd share it as TIPS.

mysql_query.rb

db = { :db_config => "~/.user.cnf", :db_name => "database_name" }

query = "SELECT * FROM db_table_name WHERE primary_key_id = 1;"
res = `/usr/bin/mysql --defaults-extra-file=#{db.fetch(:db_config)} -D #{db.fetch(:db_name)} -e \"#{query}\" `

if res.empty? then
    p "data is none."
else
    lines = res.split("\n")
    columns = lines.first.split("\t")
    results = []
    lines.each_with_index { |line, i| 
        if i > 0 then
            tmp_hash = {}
            values = line.split("\t")
            values.each_index { |j| 
                if values[j].match(/^\d+$/) then
                    tmp_hash[columns[j]] = values[j].to_i
                else
                    tmp_hash[columns[j]] = values[j].to_s
                end
            }
            results < tmp_hash
        end
    }
    p results
end

やってることは、コマンドラインでMySQLのクエリを発行しているのと同義で、標準出力としてのMySQLクエリの結果をRuby側で取り込んでハッシュにパースしているだけです。 なお、MySQL5.6からコマンドラインにパスワードを付与してmysqlコマンドを実行すると警告が出てしまうので、MySQLへの接続は.user.cnfのファイルに書いて、そっちからインポートするようにしている。

.user.cnf

[client]
user = <MySQLのユーザー名>
password = <MySQLのログインパスワード>
host = <MySQLのホスト名(RDSのエンドポイント等)>

So, when you run it,

$ ruby mysql_query.rb
[{"primary_key_id"=>1, "column_name1"=>11, "column_name2"=>2, "column_name3"=>"e76a76ec", "column_name4"=>"medium", "column_name5"=>"a", "column_name6"=>"2316e746", "column_ name7"=>"1.0.0", "datetime"=>"2014-09-29 10:41:35", "status"=>"done", "description"=>"NULL"}]
$ 

and the MySQL query execution result returns an array with the hash of the column name as the key. If you argue a query and make it a function, it may also be used as a simple CRUD... But after all, there will be almost no need (^_^;</MySQLのホスト名(RDSのエンドポイント等)></MySQLのログインパスワード></MySQLのユーザー名>

Related Articles