Question

I'm trying to get the Postgre DBI to work with Ruby, and haven't located the authoritative answer yet, but am hoping to find that help here...

Here's the code producing the error:

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

And here's the error message:

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)

I'm not sure of the correct classname to use; Pgconn was a guess.

But further testing shows this simple test also failed:

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

Which fails with:

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

Now, I think I have the postgres gem installed ok:

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

So, I'm at a loss as to

  1. do I have the right Postgres driver and DBI installed?
  2. why my first test program above fails?
Was it helpful?

Solution

Could it be as simple as a Pgconn::PGError when you just mean PGError? This:

rescue Pgconn::PGError => e

should be

rescue PGError => e

And you want:

require 'pg'

as in your first sample, not require 'postgres'.

The documentation is online:

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

OTHER TIPS

Require RubyGems before you require the PG gem, e.g.

require 'rubygems'
require 'pg'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top