Python PostgreSQL Tutorial – Getting Started with PostgreSQL and psycopg2
Last updated 1 month ago | 124 views 75 5

PostgreSQL is a powerful, open-source object-relational database system known for its stability and advanced features. If you’re a Python developer looking to integrate PostgreSQL into your applications, this tutorial will help you get started step-by-step using the psycopg2
library.
Table of Contents
-
What is PostgreSQL?
-
Why Use PostgreSQL with Python?
-
Prerequisites
-
Installing PostgreSQL
-
Installing
psycopg2
-
Connecting to a PostgreSQL Database
-
Creating a Table
-
Inserting Data
-
Querying Data
-
Full Example
-
Tips and Common Pitfalls
1. What is PostgreSQL?
PostgreSQL (or Postgres) is an advanced relational database system that supports:
-
Complex queries
-
Foreign keys
-
Triggers and stored procedures
-
JSON data types
-
Concurrency without read locks
2. Why Use PostgreSQL with Python?
Python and PostgreSQL are a popular combination for building web applications, data pipelines, and analytics dashboards. With libraries like psycopg2
, integration is straightforward and powerful.
✅ 3. Prerequisites
-
Python 3.x installed
-
PostgreSQL installed and running locally or on a server
-
Basic knowledge of SQL and Python
4. Installing PostgreSQL
Windows/macOS/Linux
Download and install from the official website:
https://www.postgresql.org/download/
During installation:
-
Choose a username (
postgres
by default) -
Set a password
-
Remember the port (default is 5432)
You can also use tools like pgAdmin for GUI management.
5. Installing psycopg2
Install the PostgreSQL adapter for Python using pip:
pip install psycopg2-binary
6. Connecting to a PostgreSQL Database
import psycopg2
# Connect to PostgreSQL
conn = psycopg2.connect(
dbname="your_db",
user="postgres",
password="your_password",
host="localhost",
port="5432"
)
# Create a cursor
cur = conn.cursor()
Replace "your_db"
and "your_password"
with your credentials.
7. Creating a Table
Let’s create a table called students
:
cur.execute("""
CREATE TABLE IF NOT EXISTS students (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
age INT,
grade VARCHAR(10)
)
""")
conn.commit()
8. Inserting Data
Insert a student into the table:
cur.execute("""
INSERT INTO students (name, age, grade)
VALUES (%s, %s, %s)
""", ("Alice", 22, "A"))
conn.commit()
Always use parameterized queries to prevent SQL injection.
9. Querying Data
Retrieve data from the table:
cur.execute("SELECT * FROM students")
rows = cur.fetchall()
for row in rows:
print(row)
10. Full Example – Python PostgreSQL Getting Started
import psycopg2
# Connect to PostgreSQL
conn = psycopg2.connect(
dbname="your_db",
user="postgres",
password="your_password",
host="localhost",
port="5432"
)
cur = conn.cursor()
# Create table
cur.execute("""
CREATE TABLE IF NOT EXISTS students (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
age INT,
grade VARCHAR(10)
)
""")
# Insert a record
cur.execute("""
INSERT INTO students (name, age, grade)
VALUES (%s, %s, %s)
""", ("Bob", 23, "B"))
# Query records
cur.execute("SELECT * FROM students")
students = cur.fetchall()
for student in students:
print(student)
# Clean up
conn.commit()
cur.close()
conn.close()
11. Tips and Common Pitfalls
Tip / Pitfall | Explanation |
---|---|
✅ Always commit after insert/update | Changes aren’t saved until you call conn.commit() |
❌ Don’t hardcode passwords | Use environment variables or config files |
✅ Use with for better resource management |
Ensures connections and cursors are properly closed |
❌ Avoid string interpolation in SQL | Use placeholders (%s ) for safety |
✅ Handle exceptions | Wrap DB logic in try-except blocks |
Conclusion
You're now ready to start using PostgreSQL with Python! Whether you're building data-heavy applications, APIs, or reporting tools, psycopg2
offers a stable and secure way to interact with PostgreSQL.
Next steps:
-
Learn about parameterized queries
-
Use connection pooling with
psycopg2.pool
-
Explore ORMs like SQLAlchemy for more advanced use cases