Skip to content
import psycopg2
from psycopg2 import sql

# Connect to PostgreSQL server
conn = psycopg2.connect(
    dbname="postgres",
    user="your_username",
    password="your_password",
    host="localhost",
    port="5432"
)
conn.autocommit = True
cur = conn.cursor()

# Create a new database
cur.execute("DROP DATABASE IF EXISTS sample_db")
cur.execute("CREATE DATABASE sample_db")

# Close the initial connection
cur.close()
conn.close()

# Connect to the new database
conn = psycopg2.connect(
    dbname="sample_db",
    user="your_username",
    password="your_password",
    host="localhost",
    port="5432"
)
cur = conn.cursor()

# Create a sample table
cur.execute("""
    CREATE TABLE users (
        id SERIAL PRIMARY KEY,
        name VARCHAR(100),
        email VARCHAR(100),
        age INT
    )
""")

# Insert sample data
cur.execute("""
    INSERT INTO users (name, email, age) VALUES
    ('Alice', '[email protected]', 30),
    ('Bob', '[email protected]', 25),
    ('Charlie', '[email protected]', 35)
""")

# Commit changes and close the connection
conn.commit()
cur.close()
conn.close()