Setup POSTGRES with Python ๐Ÿ

ยท

1 min read

Postgres Download

Download POSTGRES

Psycopg2

import psycopg2

Simple Python Script to connect with POSTGRES DB

import psycopg2

## Connect to the DB

connection
 = psycopg2.connect(
        host = "127.0.0.1",
                port = "5432",
        database = "postgres",
        user="postgres",
        password="your_chosen_password"
)

Python Script to create database

....

connection.autocommit = True # "autcommit" set to True, so you don't have to commit your queries.
cursor = connection.cursor()

# Create Database Query
# Suppose we are asking user to choose, name of the database,

database_name = str(input("Database Name: "))
create_db_query = f'''
                                        CREATE DATABASE {database_name}
                                    '''

#Execute Query
cursor.execute(create_db_query)

Python Script to drop database

....

connection.autocommit = True # "autcommit" set to True, so you don't have to commit your queries.
cursor = connection.cursor()

# DROP Database Query
# Suppose we are asking user to choose, name of the database,

database_name = str(input("Database Name: "))
create_db_query = f'''
                                        DROP DATABASE {database_name}
                                    '''

#Execute Query
cursor.execute(create_db_query)

Thanks a lot for staying with me up till this point, I hope you enjoy reading this article.

ย