【问题标题】:display postgres sql result using pg gem使用 pg gem 显示 postgres sql 结果
【发布时间】:2015-09-10 04:11:29
【问题描述】:

如何仅使用 pg gem 显示 postgres 查询的结果集?我希望它像在 pgAdmin GUI 工具中一样采用表格形式。下面的代码没有帮助。文档不清楚,所以我无法找到其他出路。请帮忙!

require 'pg'
conn = PGconn.connect("db.corp.com", 5432, '', '', "schema", "user", "pass")
sql = 'select * from tbl limit 2'
res  = conn.exec(sql)

res.each do |row|
    row.each do |column|    
    end
end

宝石清单 - pg (0.9.0.pre156 x86-mswin32)

红宝石 - 1.8.7

【问题讨论】:

  • 我认为您对 PG gem 的功能抱有非常不切实际的期望。它只是一个查询 postgres 服务器的客户端。如果您想获得漂亮的 GUI 输出,您实际上需要自己构建它或使用其他一些 gem。
  • @maxcal - 为什么他们有这么原始的宝石?我可以为此使用活动记录吗?
  • PG 是一个低级组件,有点像汽车的引擎。您不希望引擎有舒适的座椅或 GPS。好的软件也是如此——许多不同的部分都在协同工作。它与 ActiveRecord 相同 - 它的级别更高一些,因为您使用模型而不是 RAW SQL,但它不是您正在寻找的捷径。

标签: ruby postgresql pg


【解决方案1】:

步骤 - 1. 获取结果集中的列名列表(类型 PGResult)。 2. 迭代结果集的每一行(散列)。 3. 对于步骤 1 中找到的每一行(哈希键)/列,找到列值(哈希值)。

然后将结果打印为 csv。我不认为这很有效,但它可以完成工作。

require 'pg'
conn = PGconn.connect("db.corp.com", 5432, '', '', "schema", "user", "pass")
sql = 'select * from tbl limit 2'
res  = conn.exec(sql)

rows_count = res.num_tuples
column_names = res.fields
col_header = column_names.join(', ')

puts col_header

for i in 0..rows_count-1
    row_hash = res[i]
    row_arr = []
    column_names.each do |col|
        row_arr << row_hash[col]
    end
    row = row_arr.join(', ')
    puts row
end

【讨论】:

    猜你喜欢
    • 2017-10-06
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 2016-11-19
    • 2016-09-17
    • 1970-01-01
    相关资源
    最近更新 更多