FILE: create_table.py
import psycopg2 conn = psycopg2.connect(database = "kwikl3arn", user = "postgres", password = "post123", host = "localhost", port = "5432") conn.autocommit = True print ("Opened database successfully") cur = conn.cursor() cur.execute('CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))') print ("created table successfully") conn.close()
RUN:
C:\Users\Your Name>python create_table.py Opened database successfully created table successfully
FILE: table_list.py
import psycopg2 conn = psycopg2.connect(database = "kwikl3arn", user = "postgres", password = "post123", host = "localhost", port = "5432") print ("Opened database successfully") cur = conn.cursor() cur.execute("SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'") rows = cur.fetchall() for row in rows: print (row[0]) conn.close()
C:\Users\Your Name>python table_list.py Opened database successfully customers
If the table already exists, use the ALTER TABLE keyword
FILE: alter_table.py
import psycopg2 conn = psycopg2.connect(database = "kwikl3arn", user = "postgres", password = "post123", host = "localhost", port = "5432") conn.autocommit = True print ("Opened database successfully") cur = conn.cursor() cur.execute("ALTER TABLE customers ADD COLUMN id SERIAL PRIMARY KEY ") conn.close()
C:\Users\Your Name>python alter_table.py Opened database successfully