Loading...

Python PostgreSQL

Python PostgreSQL Create Database

Creating a Database

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:

  • Use the connect() method of psycopg2 with required arguments to connect PostgreSQL.
  • Create a cursor object using the connection object returned by the connect method to execute PostgreSQL queries from Python.
  • Close the Cursor object and PostgreSQL database connection after your work completes.
  • The autocommit mode is useful to execute commands requiring to be run outside a transaction, such as CREATE DATABASE

Showing list of 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()

RUN:

C:\Users\Your Name>python databse_list.py

Opened database successfully
show in List of Database
books
kwikl3arn

Connecting to Database

  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()

RUN:

C:\Users\Your Name>python database_connect.py

Opened database successfully

If the database does not exist, you will get an error.