【问题标题】:Create Postgresql database in Heroku with Ruby (without Rails)使用 Ruby(不带 Rails)在 Heroku 中创建 Postgresql 数据库
【发布时间】:2015-07-15 03:31:08
【问题描述】:

我目前正在托管一个简单的 Ruby 脚本,用于存储 URL 和分数并将它们保存到 YAML。但是,我想保存到 Postgresql 数据库,因为每次重新启动应用程序时都会删除 yaml 文件。这是我在 Heroku 中遇到的错误:

could not connect to server: No such file or directory (PG::ConnectionBad)

这是一个在本地工作的示例脚本,但在 Heroku 中引发了上述错误:

require 'pg'
conn = PG.connect( dbname: 'template1' )
res1 = conn.exec('SELECT * from pg_database where datname = $1', ['words'])
if res1.ntuples == 1 # db exists
  # do nothing
else
  conn.exec('CREATE DATABASE words')
  words_conn = PGconn.connect( :dbname => 'words')
  words_conn.exec("create table top (url varchar, score integer);")
  words_conn.exec("INSERT INTO top (url, score) VALUES ('http://apple.com', 1);")
end

提前感谢您的任何帮助或建议!

【问题讨论】:

    标签: ruby postgresql heroku


    【解决方案1】:

    假设您通过heroku addons:add heroku-postgresql:dev(或您选择的计划)使用Heroku 工具链创建了一个Postgres 数据库,您应该有一个包含您的连接字符串的DATABASE_URL 环境变量。你可以通过heroku pg:config在本地查看。

    使用pg gem(文档:http://deveiate.org/code/pg/PG/Connection.html) - 并从那里修改示例以适应 -

    require 'pg'
    # source the connection string from the DATABASE_URL environmental variable
    conn = PG::Connection.new(ENV['DATABASE_URL'])
    res = conn.exec_params('create table top (url varchar, score integer;")
    

    更新:一个稍微更完整的错误处理示例:

    conn = PG::Connection.new(ENV['TEST_DATABASE_URL'])
    begin
        # Ensures the table is created if it doesn't exist
        res = conn.exec("CREATE TABLE IF NOT EXISTS top (url varchar, score integer);")
        res.result_status
    rescue PG::Error => pg_error
        puts "Table creation failed: #{pg_error.message}"
    end
    

    【讨论】:

    • 谢谢!这非常有效!在我之前的代码中,我使用我的 res1 PG::Result 变量来检查数据库是否存在(使用 ntuples == 1)。如何重构它以使用您的示例?再次感谢!
    • 数据库已经为您创建好了:如果您检查heroku pg:credentials 的结果,您会发现数据库名称被定义为DATABASE_URL 的一部分。否则,try/rescue 块可以在初始化期间捕获任何其他终端错误。请参阅我的更新以获取快速示例。
    • @LeeCarl 数据库 URL 包含开始使用它所需的一切:协议名称、服务器主机名和端口、用户凭据和数据库名称。由于 DBaaS 为您生成所有这些,因此将所有这些作为一大块信息提供是有意义的。确实如此。
    • 救援块正是我所需要的。感谢大家的帮助! :3
    猜你喜欢
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    相关资源
    最近更新 更多