简体   繁体   中英

Unable to connect to postgresQL with Ruby

I've searched in the archive but could not find an answer to my dilemma. I'm coding in Ruby and using watir webdriver framework on my local Mac Yosemite and want to connect to postgres database on a linux box.

I have the required ruby gems installed on my local Mac

* LOCAL GEMS *

  • dbd-pg (0.3.9)
  • pg (0.18.4)
  • dbi (0.4.5, 0.4.4)

I am using the following code.

require 'rubygems'
require 'pg'
require 'dbd/pg'
require 'dbi'
conn = PGconn.connect("10.0.xx.xx","5432",'','',"mydbname","dbuser", "") 
res  = conn.exec('select *  from priorities_map;') 
puts res.getvalue(0,0)    
conn.close if conn  

On running this I a getting these errors

.initialize': Could not connect to server: Connection refused (PG::ConnectionBad)

Is the server running on host "10.0.xx.xx" and accepting
TCP/IP connections on port 5432?

If I use the code

 dbh = DBI.connect("dbi:pg:mydbname:ipaddress", "user", "")
 row = dbh.exec('select * from etr_priorities_map;') 
 puts row.getvalue(0,0)
 dbh.disconnect if dbh

I get the error

block in load_driver': Unable to load driver 'pg' (underlying error: wrong constant name pg) (DBI::InterfaceError)  from System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/monitor.rb:211:in `mon_synchronize'

I am new to Ruby. How can I resolve these issues?

The first error, as @Doon said in the comments, comes from the TCP connection and usually means your database is not listening on the network. Most PostgreSQL packages come with a default configuration that only allows local connections, but you can enable connections over the network in the server configuration via the listen_addresses setting. I installed PostgreSQL through Homebrew on my Mac, and my config is at /usr/local/var/postgres/postgresql.conf , but if you installed it some other way the path may be different.

The second error is happening because the "driver" part of the connection string is case-sensitive , and the DBD driver for Postgres is named Pg , not pg . Try this:

dbh = DBI.connect("dbi:Pg:mydbname:ipaddress", "user", "")

Also, unless you have your heart set on using Ruby/DBI , you might want to consider using a more-recently maintained library. Ruby-DBI is very well-written and tested, but it hasn't seen a release since 2010, and Ruby itself has changed pretty significantly in the interim.

If you do want to consider alternatives, I use Sequel for mostly everything, and I highly recommend it, especially for Postgres development, but both DataMapper and ActiveRecord have a large userbase as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM