how to connect postgresql database to django code example

Example 1: how to connect postgres database to python

import psycopg2
try:
    connection = psycopg2.connect(user = "sysadmin",
                                  password = "pynative@#29",
                                  host = "127.0.0.1",
                                  port = "5432",
                                  database = "postgres_db")

    cursor = connection.cursor()
    # Print PostgreSQL Connection properties
    print ( connection.get_dsn_parameters(),"\n")

    # Print PostgreSQL version
    cursor.execute("SELECT version();")
    record = cursor.fetchone()
    print("You are connected to - ", record,"\n")

except (Exception, psycopg2.Error) as error :
    print ("Error while connecting to PostgreSQL", error)
finally:
    #closing database connection.
        if(connection):
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")

Example 2: postgres django

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'your_database_project_name',
        'USER': 'your_postgres_username',
        'PASSWORD': 'your_postgres_password',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

Example 3: connecting to a new database using postgresql sql shell

For Windows users using the SQL shell

\c DB_NAME USER_NAME HOST PORT

// to get the connection details such as your username, host and port simply use the "\conninfo" command

eg : \c test1 john_doe localhost 5432

Example 4: setting up a django prostgress project

env/scripts/activate

Tags:

Sql Example