gpt4 book ai didi

ruby - 使用 pg gem 显示 postgres sql 结果

转载 作者:行者123 更新时间:2023-11-29 13:00:43 26 4
gpt4 key购买 nike

如何仅使用 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

gem list -pg (0.9.0.pre156 x86-mswin32)

ruby - 1.8.7

最佳答案

步骤 -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

关于ruby - 使用 pg gem 显示 postgres sql 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31018408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com