简体   繁体   中英

How do I connect to a postgres database with Sequel?

I was making a web app to deploy using Heroku.com when I realized that the only database type they support is PostgreSQL. Up until now, my app (powered by the Ruby gem Sinatra) accessed the database via the .Sqlite method for the Sequel gem.

Here's my Ruby script from when I used Sequel to access the .db file via SQLite:

DB = Sequel.sqlite('mydatabase.db')
DB.create_table :mytable do
  primary_key :id
  String :column_name
end


I installed PostgreSQL after learning Heroku used only that. Here's the script via postgres (my username is literally 'postgress', though I obviously won't reveal my password in this question):

DB = Sequel.postgres('mydatabase.db',:user=>'postgres',:password=>'my_password_here',:host=>'localhost',:port=>5432,:max_connections=>10)
DB.create_table :mytable do
  primary_key :id
  String :column_name 
end

However, when I run this code, I get the following error:

C:/Ruby193/lib/ruby/gems/1.9.1/gems/sequel-3.38.0/lib/sequel/adapters/postgres.rb:208:in 'initialize': PG::Error: FATAL: database "mydatabase.db" does not exist (Sequel::DatabaseConnectionError)

I've tried searching Google, StackOverflow, Sequel documents, and the Heroku help documents for any help, but I've found no fix to this problem.

Does anyone know what I am doing wrong?

The database mydatabase.db doesn't exist, as per the error message from Pg. Likely reasons:

  • You probably meant mydatabase without the SQLite-specific .db filename suffix
  • It's possible you created the db with different case, eg "Mydatabase.db" ;
  • You might be connecting to a different Pg server than you think you are
  • You never created the database . Unlke SQLite's default behaviour, Pg doesn't create databases when you try to connect to a database that doesn't exist yet.

If in doubt, connect to Pg with psql and run \\l to list databases, or connect via PgAdmin-III.

The PostgreSQL documentation and tutorial are highly recommended, too. They're well written and will teach you a lot about SQL in general as well as Pg in particular.

BTW, the postgres user is a superuser. You should not be using it for your application; it's like running your server as root, ie a really bad idea. Create a new PostgreSQL user without superuser, createdb or createuser rights and use that for your application. You can either CREATE DATABASE somedb WITH OWNER myappuser - or preferably, create the database owned by a different user to your webapp user and then expicitly GRANT the webapp user the minimum required permissions. See user management and GRANT .

在heroku上,您需要做的就是告诉Sequel连接到DATABASE_URL环境变量的内容(这是Sequel理解的正确形成的URL):

DB = Sequel.connect(ENV['DATABASE_URL']) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM