Search code examples
ruby

How to Connect the Ruby to the Postgresql?


I try to connect The ruby to the postgres, but it cannot connecting ,it shows an error "uninitialized constant PGconn".

require "pg"
conn = PGconn.connect("localhost", 5432, "", "", "test1")
res = conn.exec("select * from a;")

Solution

  • The Postgres gem pg is using PG now, PGConn is obsolete. It was still there in pg 0.11.0.

    PG.connect example:

    require 'pg' 
    conn = PG.connect( dbname: 'sales' ) 
    conn.exec( "SELECT * FROM pg_stat_activity" ) do |result| 
        result.each do |row| 
            puts row.values_at('procpid', 'usename', 'current_query')
        end
    end
    

    PG.connect is a "convenience alias" for PG::Connection.new (related SO post)