【问题标题】:cannot connect to Postgres (pg) database from my Ruby Script using gem "pg"(This is not rails, just pure ruby)无法使用 gem“pg”从我的 Ruby 脚本连接到 Postgres (pg) 数据库(这不是 rails,只是纯 ruby​​)
【发布时间】:2013-09-12 04:46:58
【问题描述】:

我为我的 Mac OSX 机器下载了 postgres.app。我有一个 rails 应用程序,它连接并使用了 postgres 应用程序附带的 postgres 数据库。

现在我正在编写一个纯 Ruby 测试脚本(不是 Rails,纯 Ruby,甚至不是 Active Record)来尝试连接到 postgres 数据库实例。这些是我设置它的步骤

 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);");

我从这个link得到这个

当我运行此脚本时,出现以下错误:

   /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 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"

不知道下一步该做什么。任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: ruby postgresql rubygems database-connection pg


    【解决方案1】:

    您确定 postgres 正在侦听套接字吗?你确定用户名和密码正确吗?

    我会倾向于尝试类似的东西

    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】:

      我使用活动记录 gem 来建立连接,这很好

      【讨论】:

        【解决方案3】:

        连接设置对我有用。

        但那段代码应该是这样的

        @conn.exec("CREATE TABLE 程序 (id serial NOT NULL, name 字符(255))")

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-10-06
          • 2017-01-11
          • 2014-10-11
          • 1970-01-01
          • 1970-01-01
          • 2013-01-13
          • 1970-01-01
          • 2017-03-19
          相关资源
          最近更新 更多