[英]How to parse a SQL result and convert it to Ruby hash
我想将SQL查询结果转换为Ruby哈希,其中仅显示两行,第一行充当键,第二行充当值。 例如,如果我的查询得到以下结果:
+----+--------+ | id | name | +--- +--------+ | 1 | a | | 2 | b | | 3 | c | | 4 | d | | 5 | e | +----+--------+
我想操纵这些数据以获得像这样的Ruby哈希:
h = { '1' => 'a',
'2' => 'b'.
'3' => 'c',
'4' => 'd',
'5' => 'e' }
我该怎么做?
我在大多数非铁路项目中都使用ruby Sequel 。 这是用于SQL数据库的出色ORM 。
这是使用SQLite的代码示例(在内存中):
#!/usr/bin/env ruby
require 'sequel'
# create db in memory
DB = Sequel.sqlite
# create table
DB.create_table :items do
primary_key :id
String :name
end
# Create a dataset
items = DB[:items]
# Populate the table
items.insert(:name => 'john')
items.insert(:name => 'mike')
items.insert(:name => 'nick')
puts "#{items.all}"
# => [{:id=>1, :name=>"john"}, {:id=>2, :name=>"mike"}, {:id=>3, :name=>"nick"}]
# initialize hash object
h = {}
# Create the hash in the form you want
items.all.each do |entry|
h[entry[:id]]= entry[:name]
end
# p the hash
p h # => {1=>"john", 2=>"mike", 3=>"nick"}
注意:续集功能非常强大。 可能有一种方法可以直接执行您想做的事情,而无需将数据传递到循环中。 但是,您必须阅读文档以了解是否需要清除代码。
希望这可以帮助!
更新:这是杰里米·埃文(Sequel的作者)之后的更新代码:
#!/usr/bin/env ruby
require 'sequel'
# create db in memory
DB = Sequel.sqlite
# create table
DB.create_table :items do
primary_key :id
String :name
end
# Create a dataset
items = DB[:items]
# Populate the table
items.insert(:name => 'john')
items.insert(:name => 'mike')
items.insert(:name => 'nick')
# Return hash of items
p items.select_hash(:id, :name) # => {1=>"john", 2=>"mike", 3=>"nick"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.