I’m trying to connect to MySQL database using SQLAlchemy but getting connection errors when my password contains special characters like @ symbol.
from sqlalchemy import create_engine
import pymysql
user_name = "admin_user"
user_password = "pass@456"
database_name = "myapp_db"
server_host = "localhost"
db_engine = create_engine(
f'mysql+pymysql://{user_name}:{user_password}@{server_host}/{database_name}',
pool_pre_ping=True,
pool_recycle=300
)
This throws an error:
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '456@localhost' ([Errno -2] Name or service not known)")
The issue happens because the @ character in password gets parsed incorrectly. Here’s how I fixed it using URL encoding:
from sqlalchemy import create_engine
import pymysql
import urllib.parse
user_name = "admin_user"
user_password = "pass@456"
encoded_password = urllib.parse.quote_plus(user_password)
database_name = "myapp_db"
server_host = "localhost"
db_engine = create_engine(
f'mysql+pymysql://{user_name}:{encoded_password}@{server_host}/{database_name}',
pool_pre_ping=True,
pool_recycle=300
)
The urllib.parse.quote_plus() function properly encodes special characters in the password string, preventing connection string parsing issues.