如何从hstore返回特定的键值?

时间:2014-03-10 18:17:25

标签: ruby postgresql hstore

我有一个包含hstore作为列的psql数据库,如下所示: 柱: “a”=> “1”,“b”=> “2”,“c”=> “3”

在一个独立的ruby脚本中,我正在访问我的数据库,但是我想为“a”输出一个特定的值,所以它只返回“1”。 当我尝试从循环中执行此操作时,它输出“a”=> “1”而不是。

require 'rubygems'
require 'pg'
require 'open-uri'
require'activerecord-postgres-hstore'

conn = PGconn.connect("hostname", 1234, '', '', "x", "y", "z")

array = conn.exec('SELECT * FROM database')

  array.each do |uri|
    puts uri['column']
  end

此页面上的文档http://www.postgresql.org/docs/9.1/static/hstore.html 表明您可以使用 hstore - >文本获取值,但我不确定如何在ruby中执行此操作。

我也看到了这个问题how to parse and display hstore key/value in rails,但正如我所说,当我只想要这个值时,输出给了我关键和值。

我还应该说,虽然数据库是使用rails创建的,但我不想将它用于此脚本。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果您只想在'a'中提取column个键的值,那么请准确说明并让数据库完成工作:

conn.exec(%q{SELECT column -> 'a' FROM database}).each do |_, a|
  # The value will be in `a`, `_` will be the made up column name.
end

或者,如果您想与其他事物合作:

conn.exec(%q{SELECT other_column, column -> 'a' as col_at_a FROM database}).each do |row|
  # Look at `row['other_column']` and `row['col_at_a']` ...
end