[Python] sqlalchemy.exc.OperationalError: (2003, "Can't connect to MySQL server on...

Discussão em 'Python' iniciado por Stack, Junho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I am using python to Connect with DB.

    from sqlalchemy import create_engine
    import pymysql
    db_password = "abc@123"
    db_user = "test_user"
    db_name = "xyz"
    db_host = "127.0.0.1" # or 127.0.0.1
    # Create SQLAlchemy engine
    engine = create_engine(f'mysql+pymysql://{db_user}:{db_password}@{db_host}/{db_name}', pool_pre_ping=True, pool_recycle=300)


    Error:

    pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '123@127.0.0.1' ([Errno -2] Name or service not kn
    own)")


    Other Logs:

    (lead_prediction) bitnami@my-instance-name:~/lead_prediction$ cat /etc/hosts
    127.0.0.1 localhost

    (lead_prediction) bitnami@my-instance-name:~/lead_prediction$ netstat -tulpn | grep LISTEN
    (Not all processes could be identified, non-owned process info
    will not be shown, you would have to be root to see it all.)
    tcp 0 0 0.0.0.0:5355 0.0.0.0:* LISTEN -
    tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN -


    Ans: Alternate way to make it work: Use urllib.parse mathod to handle special character in MySQL DB Password

    from sqlalchemy import create_engine
    import pymysql
    import urllib.parse
    db_password = "abc@123"
    db_password = urllib.parse.quote_plus(db_password) # Parsing the password to avoid error: pwd: Jane@123, Error: '123@localhost' ([Errno -2] Name or service not known)")
    db_user = "test_user"
    db_name = "xyz"
    db_host = "127.0.0.1" # or 127.0.0.1
    # Create SQLAlchemy engine
    engine = create_engine(f'mysql+pymysql://{db_user}:{db_password}@{db_host}/{db_name}', pool_pre_ping=True, pool_recycle=300)

    Continue reading...

Compartilhe esta Página