1

我正在尝试让 Postgre DBI 与 Ruby 一起使用,但还没有找到权威的答案,但我希望在这里能找到帮助......

这是产生错误的代码:

#!/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:

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

所以,我不知所措

  1. 我是否安装了正确的 Postgres 驱动程序和 DBI?
  2. 为什么我上面的第一个测试程序失败了?
4

2 回答 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

于 2011-12-02T01:08:42.050 回答
0

在需要 PG gem 之前需要 RubyGems,例如

require 'rubygems'
require 'pg'
于 2011-12-02T01:14:54.077 回答