Skip to content

Instantly share code, notes, and snippets.

@lightscalar
Last active November 12, 2019 15:34
Show Gist options
  • Save lightscalar/5664dcda52b0c506215dc2df6c07a926 to your computer and use it in GitHub Desktop.
Save lightscalar/5664dcda52b0c506215dc2df6c07a926 to your computer and use it in GitHub Desktop.
Postgresql commands

To start and stop the database server:

pg_ctl -D /usr/local/var/postgres start
pg_ctl -D /usr/local/var/postgres stop

To create and drop a database:

createdb test
dropdb test

Now add a new user to test:

psql
CREATE USER galois WITH PASSWORD 's3kr3t';
GRANT ALL PRIVILEGES ON DATABASE test to galois

To connect at the command line, we can do this:

psql -U user_name -d database_name -h 127.0.0.1 -W

Here the -W flag indicates we'll be entering a password.

Now we can connect to this database in Python via SqlAlchemy as follows:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Create a new engine.
engine = create_engine('postgresql+psycopg2://galois:s3kr3t@localhost/test')
Session = sessionmaker(bind=engine)
Base = declarative_base()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment