FILE: create_database_postgres.py
import psycopg2 conn = psycopg2.connect(user = "postgres", password = "post123", host = "localhost", port = "5432") conn.autocommit = True print ("Opened database successfully") cur = conn.cursor() cur.execute("create database kwikl3arn") print ("created database successfully"); conn.close()
RUN:
C:\Users\Your Name>python create_database_postgres.py Opened database successfully Created database successfully
NOTE:
connect()
CREATE DATABASE
FILE: databse_list.py
import psycopg2 conn = psycopg2.connect(user = "postgres", password = "post123", host = "localhost", port = "5432") print ("Opened database successfully") cur = conn.cursor() cur.execute("SELECT datname FROM pg_database") rows = cur.fetchall() print ("show in List of Database") for row in rows: print (row[0]) conn.close()
C:\Users\Your Name>python databse_list.py Opened database successfully show in List of Database books kwikl3arn
FILE: database_connect.py
import psycopg2 conn = psycopg2.connect(database = "kwikl3arn",user = "postgres", password = "post123", host = "localhost", port = "5432") print ("Opened database successfully") cur = conn.cursor() conn.close()
C:\Users\Your Name>python database_connect.py Opened database successfully
If the database does not exist, you will get an error.