2011-12-02 75 views
1

我试图让Postgre DBI与Ruby的工作,并没有位于权威的答案,但我希望能找到这里帮助...如何解决Ruby的Postgres驱动程序和DBI问题?

下面的代码产生错误:

#!/usr/bin/ruby 
require 'pg' 

$maxwidth=12 

conn = PGconn.connect("localhost", 5432, '', '', "testdb", "caseyr", "genesrule") 

###### DROP ANY EXISTING rocks TABLE ###### 
    begin 
     res = conn.exec("SELECT id FROM rocks;") 
    rescue # rocks table doesn't exist -- this is legitimate 
    else # rocks table exists, so delete it 
     puts 'DELETING rocks...' 
     res = conn.exec("DROP TABLE rocks;") 
    end 

###### CREATE AND POPULATE rocks TABLE ###### 
begin 
    res = conn.exec("CREATE TABLE rocks (id serial, rockname char(20));") 
    res = conn.exec("INSERT INTO ROCKS (rockname) values ('Diamond');") 
    res = conn.exec("INSERT INTO ROCKS (rockname) values ('Ruby');") 
    res = conn.exec("INSERT INTO ROCKS (rockname) values ('Emerald');") 
rescue Pgconn::PGError => e 
    puts "Error creating and filling rocks table." 
    puts "Error code: #{e.err}" 
    puts "Error message: #{e.errstr}" 
    conn.close() if conn 
end 

而这里的错误消息:

ruby testRocks.rb 
DELETING rocks... 
NOTICE: CREATE TABLE will create implicit sequence "rocks_id_seq" for serial column "rocks.id" 

testRocks.rb:35: uninitialized constant Pgconn (NameError) 

我不知道正确的类名使用的; Pgconn是一个猜测。

但进一步的测试表明这个简单的测试也失败了:

#!/usr/bin/ruby 
require 'postgres' 

哪些失败:

ruby basictest.rb 
basictest.rb:2:in `require': no such file to load -- postgres (LoadError) 
    from basictest.rb:2 

现在,我想我已经确定安装了Postgres的宝石:

gem list | grep post 
postgres (0.7.9.2008.01.28) 
postgres-pr (0.6.3) 

所以,我不知所措

  1. 我有正确的Postgres驱动程序和DBI吗?
  2. 为什么我上面的第一个测试程序失败?

回答

2

难道它只是一个简单的Pgconn::PGError当你的意思PGError?这:

rescue Pgconn::PGError => e 

应该

rescue PGError => e 

你想:

require 'pg' 

为第一个样品,不require 'postgres'英寸

文档在线:

http://rubydoc.info/gems/pg/0.11.0/frames

+0

这有助于:我以前的错误消失了,现在得到一个不同的错误:错误选择列名。 testRocks.rb:38:未定义的方法'err'为#(NoMethodError)....所以它似乎我不是指正确的方法来获取错误消息?感谢您的帮助... – rixter

0

要求RubyGems的您所需要的PG的宝石,如前

require 'rubygems' 
require 'pg' 
+0

这似乎没有任何区别? – rixter

+0

PG是一个宝石,所以除非你通过'ruby -rrubygems'运行这个脚本,否则我看不到你是如何加载rubygems的,所以它可以反过来加载PG宝石 –