Database connection errors are common in web applications using frameworks like Django and Flask. These issues usually arise due to misconfigurations, network problems, or incorrect credentials.
Common Database Connection Errors & Fixes
1️⃣ “OperationalError: could not connect to server” (PostgreSQL, MySQL, SQLite)
Error Message (PostgreSQL Example):
django.db.utils.OperationalError: could not connect to server: Connection refused
Fix:
- Check if the database service is running:
sudo systemctl status postgresql # For PostgreSQL sudo systemctl status mysql # For MySQL
- Ensure the database is listening on the correct host and port.
2️⃣ “django.db.utils.OperationalError: database is locked” (SQLite)
Error Cause: SQLite locks the database if multiple processes try to write at the same time.
Fix:
- Avoid concurrent writes in SQLite.
- Use a different database (PostgreSQL or MySQL) for production.
- Set
timeout
in Django settings:DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / "db.sqlite3", 'OPTIONS': { 'timeout': 20 }, # Increase timeout } }
3️⃣ “ModuleNotFoundError: No module named ‘psycopg2′” (PostgreSQL with Django/Flask)
Fix: Install the missing module
pip install psycopg2-binary # For PostgreSQL
pip install mysqlclient # For MySQL
4️⃣ “Access denied for user ‘root’@’localhost'” (MySQL)
Fix:
- Ensure the username and password are correct:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydatabase', 'USER': 'root', 'PASSWORD': 'yourpassword', 'HOST': 'localhost', 'PORT': '3306', } }
- Reset the MySQL root password:
mysql -u root -p ALTER USER 'root'@'localhost' IDENTIFIED BY 'newpassword';
5️⃣ “TimeoutError: SQL query took too long to respond”
Fix:
- Optimize queries using indexing:
CREATE INDEX idx_name ON table_name (column_name);
- Use connection pooling in Django:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydb', 'USER': 'myuser', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', 'CONN_MAX_AGE': 600, # Persistent connections } }
6️⃣ “ProgrammingError: relation does not exist” (PostgreSQL, Django)
Error Cause: The table does not exist due to missing migrations.
Fix:
- Run migrations:
python manage.py makemigrations python manage.py migrate
- If using Flask, run:
flask db migrate flask db upgrade
Debugging Steps
- Check if the database is running:
udo systemctl status postgresql # PostgreSQL sudo systemctl status mysql # MySQL
- Check database logs for errors:
tail -f /var/log/postgresql/postgresql.log # PostgreSQL tail -f /var/log/mysql/error.log # MySQL
- Test connection manually:
psql -U myuser -d mydb -h localhost # PostgreSQL mysql -u myuser -p mydb # MySQL