2015-07-13 19 views
0

我想寫一個簡單的Ruby腳本,它將字符串和整數存儲在Postgresql數據庫中。這是我想它是如何工作的:在Ruby中創建和訪問Postgres(不含Rails)

require 'pg' 
# if database 'Words' exists 
# name = 'Bud' 
# score = 99 
# replace String1 with 'Bud' and Integer1 with 99 if score > Integer1 
# else 
# CREATE database 'Words' 
# INSERT INTO Words (String1, Integer1) 
# VALUES ('Dave', 30) 
# end 

我想基本上訪問該數據庫,你會簡單數組或哈希。我想使用Postgres而不是YAML文件的原因是因爲YAML文件不會保留在免費的heroku帳戶上。

+0

你到目前爲止嘗試了什麼?我假設一個基本的搜索應該給你一個基本的例子 –

+0

你只是'插入'到表中,而不是「數據庫」。我認爲你在混合使用術語「表」和「數據庫」。 –

回答

0

你可以做這樣的事情:

# Connect to the template1 db (built in) 
conn_template1 = PG.connect(dbname: 'template1') 
res1 = conn.exec('SELECT * from pg_database where datname = $1', ['words']) 
if res1.ntuples == 1 # db exists 
    conn_words = PG.connect(dbname: 'words') 
    # ... do stuff to your DB 
    conn_words.exec('INSERT INTO words ....') 
else 
    conn.exec('CREATE DATABASE words') 
end 

希望幫助!

+0

我現在要玩這個。感謝您的及時響應! – LeeCarl

+0

沒問題!請接受答案,如果它適合你:) –

+0

謝謝丹。我能夠使我的本地機器上的一切工作。但是,當我將腳本部署到Heroku時,出現「初始化」錯誤:無法連接到服務器:沒有這樣的文件或目錄(PG :: ConnectionBad)「 – LeeCarl