0

I am trying to create a postgresql database via sqlalchemy in pycharm (running python 3.6) but have trouble connecting / creating the database.

I initially started with sqlalchemy tutorial:

from sqlalchemy import create_table


engine =create_engine("postgresql+psycopg2://scott:tiger@localhost/test")
connection = engine.connect()
connection.close()

But it print's the error: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?

How should I be opening up the port, or pointing it to the localhost?

Is there any specific thing that I need to do to create the database before i run create_engine?

I've also been searching online and found that perhaps I should be using psycopg2 to create the database, but I don't understand how this is to be done.

What I would like is to create a postgresql database on my desktop, in a specific folder.

jake wong
  • 4,909
  • 12
  • 42
  • 85

1 Answers1

1

Assuming you have the psycopg2 connector installed, then all you need to specify in the the connection string is postgresql, so your connection string would be something like

postgresql://tim:xyzzy@somehost/somedb

By default, PostgreSQL only listens on the localhost IP address, 127.0.0.1. So if the PostgreSQL server is on a different system you will need to configure the listen address in postgresql.conf

You will also need to have created the database before attempting to connect to it with SQLAlchemy. So you need to so a createdb when logged in as the PostgreSQL user.

tim@merlin:~$ sudo -i -u postgres
postgres@merlin:~$ createdb foo
postgres@merlin:~$ 
TimGJ
  • 1,584
  • 2
  • 16
  • 32
  • Hmm, how do I create a postgres database in windows? – jake wong May 01 '17 at 08:12
  • If PostgreSQL is already on your Windows there should be a tool called pgAdmin. Try running that and creating a database. – TimGJ May 01 '17 at 08:17
  • So unlike `sqlite`, which can create the database through `sqlalchemy`, `postgresql database` cannot be created through `sqlalchemy` and can only be created through `pgAdmin`? – jake wong May 01 '17 at 08:21
  • Not sure, to be honest. You could connect as the postgres user and issue a CREATE DATABASE statement, although this seems like more work than simply using pgAdmin. Check out http://stackoverflow.com/questions/6506578/how-to-create-a-new-database-using-sqlalchemy for more details. – TimGJ May 01 '17 at 08:33