cannot connect to Postgres (pg) database from my Ruby Script using gem “pg”(This is not rails, just pure ruby)

元气小坏坏 提交于 2019-12-08 05:17:35

问题


I downloaded the postgres.app for my Mac OSX machine. I have a rails app that has connected and used the postgres DB that came with the postgres app.

Now I am writing a pure Ruby test script (Not Rails, pure Ruby, not even Active Record) to try to connect to the postgres database instance. These are the steps I followed to set this up

 1) ran this command on the terminal:
    gem install pg -- --with-pg-config=/Applications/Postgres.app/Contents/MacOS/bin/pg_config

 2) Added this code to the test script:

   #!/usr/bin/env ruby
   #encoding: utf-8
   require "pg"


    @conn = PG.connect(
    :dbname => 'oData',
    :user => 'am',
    :password => '')

    @conn.exec("CREATE TABLE programs (id serial NOT NULL, name character varying(255);");

I got this from this link

When I ran this script I get the following error:

   /Users/am/.rvm/gems/ruby-2.0.0-p247/gems/pg-0.16.0/lib/pg.rb:38:in `initialize': could 
    not connect to server: No such file or directory (PG::ConnectionBad)
Is the server running locally and accepting
connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?

My Debug efforts:

  My postgres.app is up and running. 

  I looked at the pg gem [documentation][2] and my syntax seemed OK.

  The location of my postgres DB is entered in my bash script like so
   PATH="/Applications/Postgres.app/Contents/MacOS/bin:$PATH"

Not sure what to do next. Any help would be appreciated, Thanks.


回答1:


are you sure postgres is listening on a socket? are you sure the username and password is right?

I would be inclined to try something like

require 'pg'

puts PG::Connection.ping(:dbname => 'oData',:user => 'am',:password => '')
puts "trying with tcp"
puts PG::Connection.ping(:dbname => 'oData',:user => 'am',:password => '', :port => 5432)



回答2:


I used active record gem to make the connection work and it was fine




回答3:


Settings to connect works for me.

But that code should look like

@conn.exec("CREATE TABLE programs (id serial NOT NULL, name character(255))")



来源:https://stackoverflow.com/questions/18685649/cannot-connect-to-postgres-pg-database-from-my-ruby-script-using-gem-pgthis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!