最新版本的'pg'gem以随机顺序返回db查询列的结果是否正常?我希望'pg'gem的行为与mysql2 gem的行为方式相同,在通过命令行直接查询数据库时按照呈现的顺序返回数据。也许有一个更好的宝石,我应该使用。以下结果的示例是使用相同查询“select * from books”
的结果首次执行:
"The Shining","9","7808","4156"
"Dune","15","4513","1866"
"2001: A Space Odyssey","15","4267","2001"
"The Cat in the Hat","2","1608","1809"
"Bartholomew and the Oobleck","2","1590","1809"
第二次执行:
"4156","The Shining","9","7808"
"1866","Dune","15","4513"
"2001","2001: A Space Odyssey","15","4267"
"1809","The Cat in the Hat","2","1608"
"1809","Bartholomew and the Oobleck","2","1590"
第三次执行:
"9","The Shining","7808","4156"
"15","Dune","4513","1866"
"15","2001: A Space Odyssey","4267","2001"
"2","The Cat in the Hat","1608","1809"
"2","Bartholomew and the Oobleck","1590","1809"
返回结果的代码:
confrom = PG::Connection.new(:user => <myuser>, :password => <mypw>, :port => 5432, :host => <myhost>, :dbname => 'booktown')
results = confrom.exec("select * from books")
results.each do |row|
row.each_value do |x|
puts x
end
end
答案 0 :(得分:5)
我猜你正在使用Ruby 1.8.X,其中Hashes没有任何已定义的顺序。我尝试使用pg
和Ruby 1.9.3的类似代码,每次都以相同的顺序出现。
在这里:
results.each do |row|
#...
end
row
将是一个简单的Hash
。因此,当您row.each_value
时,您不能依赖于Ruby 1.8中以任何特定顺序出现的x
值;在1.9中,您应该按插入顺序获取x
值。
但无论如何所有这些都无关紧要:
select * ...
,除非你在数据库内手动拨动;你应该总是说select c1, c2, ...
,这样你就可以准确地知道你从数据库中获得了什么,以及一切都会出现的顺序。如果有人添加了一列或者一列改变了位置,那么你的所有代码都会中断。 Hash
中有一个row
,因此您可以按名称访问结果,这比使用位置更容易,更容易出错。