Ruby中采用PG访问Postgresql表及function

来源:互联网 发布:常用的python ide 编辑:程序博客网 时间:2024/06/05 14:09

原文:Rails access the pg db

在rails和ruby中,在我查找要访问postgresql时,总是发现所需要的库为: gem install postgres-pr,gem install postgres,也就是使用postgres这个库来完成与pg交的数据交换,当我采用ruby 直接使用 require 'postgres' 时发现最新的postgres要降版本才可以去ruby调用,具体的原因没找到,因为降版本时根本没办法那个postgres库的版本安装起来,所以就查rails new test -d=postgresql生成的源代码,才发现rails中用的是pg这个库,故而直接用pg这个库实现pg访问和存储过程。

require 'pg'

class Testpg

# To change this template use File | Settings | File Templates.

#dbh = PGConn.connect("",5432,"postgres","400hao.cn","mytest_development")

conn = PG.connect( :dbname => 'mytest_development', :host => 'localhost', :port => 5432,:user => 'postgres' , :password => 'mypassword' )

res = conn.query("SELECT getallblogs(\'myref\');fetch all from myref;")

#res = conn.query("SELECT * FROM \"public\".blogs;")

#res = conn.query("")

#循环列出所有行和列

res.values.collect do |row|

puts row.collect {|col| "%-15s" % [col] }.join( '' )

end

#遍历每条记录的name值

res.each do |row|

puts row["name"]

end

res.clear

conn.close

end