Ruby 解析mysql2 gem选择查询
我试图使用mysql2 gem解析查询的一些输出 在此之前,我将使用:Ruby 解析mysql2 gem选择查询,ruby,mysql2,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 输出 “类别”至:“标签”和“计数”至:“值” results
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
输出
“类别”至:“标签”和“计数”至:“值”
results = db.query(sql)
results.map do |row|
{label: row['Category'], value: row['count'].to_i} }
end
期望输出
您的代码中有两个错误: 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)
请注意,您的输出表明“count”字段已经是int,因此调用_i()是多余的
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}]