如何仅使用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)
ruby - 1.8.7
答案 0 :(得分:2)
然后将结果打印为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