This project demonstrates basic CRUD (Create, Read, Update, Delete) operations with PostgreSQL using Python and the psycopg2
library.
Lucien Chemaly
- Python 3.x
- PostgreSQL database
- psycopg2 library
- Clone this repository:
git clone https://github.com/See4Devs/python-postgres-crud.git
cd python-postgres-crud
- Create and activate a virtual environment:
For Windows:
python -m venv venv
.\venv\Scripts\activate
For macOS/Linux:
python3 -m venv venv
source venv/bin/activate
- Install the required package:
pip install psycopg2-binary
- Verify the installation:
pip list
Before running the scripts, update the database connection parameters in db_connect.py
:
conn = psycopg2.connect(
host="YOUR_HOST",
database="postgres",
user="YOUR_USER",
password="YOUR_PASSWORD",
port=5432
)
db_connect.py
- Database connection utilitytest_connection.py
- Test database connectivityinsert_user.py
- Insert a single userinsert_many_users.py
- Bulk insert multiple usersupdate_user.py
- Update user informationdelete_user.py
- Delete a user
python test_connection.py
- Insert a single user:
python insert_user.py
- Insert multiple users (20 users by default):
python insert_many_users.py
python update_user.py
python delete_user.py
The project assumes a users
table with the following structure:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
All operations include basic error handling and will:
- Print success messages on successful operations
- Print error messages if operations fail
- Properly close database connections
- Always use parameterized queries to prevent SQL injection
- Properly close database connections after use
- Use transactions for data consistency
- Implement error handling for database operations
Feel free to submit issues and enhancement requests!