解析mysql2 gem的SELECT查询

时间:2013-09-05 02:00:26

标签: ruby mysql2

我正在尝试使用mysql2 gem解析查询中的一些输出。

以前,我会使用:

response = JSON.parse(response.body)
a = response.map{|s| {label: s['Category'], value: s['count'].to_i} }

现在使用mysql2查询:

results = db.query(sql)
results.map do |row|
  puts row
end

输出

{"Category"=>"Food", "count"=>22}
{"Category"=>"Drinks", "count"=>12}
{"Category"=>"Alcohol", "count"=>9}
{"Category"=>"Home", "count"=>7}
{"Category"=>"Work", "count"=>2}

'类别'到':标签'和'计数'到':值'。

results = db.query(sql)
results.map do |row|
  {label: row['Category'], value: row['count'].to_i} }
end

所需输出

{:label=>"Food", :value=>22}
{:label=>"Drinks", :value=>12}
{:label=>"Alcohol", :value=>9}
{:label=>"Home", :value=>7}
{:label=>"Work", :value=>2}

1 个答案:

答案 0 :(得分:2)

您的代码中有两个错误:

1)你有两个结束括号:

                                               #   HERE
                                               #   | |
results.map do |row|                           #   V V
  {label: row['Category'], value: row['count'].to_i} }
end

2)map()返回一个数组,并且你不将数组保存在任何地方,所以ruby丢弃它。

records = results.map do |row|
  {label: row['Category'], value: row['count'].to_i }
end

p records

以下是证据:

mysql> select * from party_supplies;
+----+----------+-------+
| id | Category | count |
+----+----------+-------+
|  1 | Food     |    22 |
|  2 | Drinks   |    12 |
+----+----------+-------+
2 rows in set (0.00 sec)

require 'mysql2'

client = Mysql2::Client.new(
  host: "localhost", 
  username: "root",
  database: "my_db",
)

results = client.query("SELECT * FROM party_supplies")


records = results.map do |row|
  { label: row['Category'], value: row['count'] }
end

p records


--output:--
[{:label=>"Food", :value=>22}, {:label=>"Drinks", :value=>12}]

请注意,您的输出表明'count'字段已经是int,因此调用to_i()是多余的。