[Python] No connection to MySQL-database - PythonAnywhere/ Beginners Plan

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

  1. Stack

    Stack Membro Participativo

    Attempt to connect to MySQL-database by module MySQLdb fails and will be responded by: name 'MySQLdb' is not defined... in the servers log. Environment is not virtual, framework is Flask

    The connection attempt via MySQLdb.connect(<credentials>) is in a try/except-clause and an exception will be thrown. In order to verify the correct credentials I entered host/user/password/database in the bash-console and the connect-function returned True for connect-state (=connected). But when running this in the Flask-App, then the server returns the above error message.

    from flask import Flask
    try:
    import MySQLdb
    except Exception as e:
    print("A problem with import MySQLdb......", e)

    def checkDBConnection():
    try:
    cnx = MySQLdb.connect(
    host = '<myUserName>.mysql.eu.pythonanywhere-services.com',
    user = '<myUserName>',
    password = '<myPW>',
    database = '<userName>$sensorData'
    )
    return True
    except Exception as e:
    print("Database error: ", e)
    return False

    app = Flask(__name__)
    #application = Flask(__name__) # see hint in *.wsgi file

    @app.route("/sensorData/<val>")
    def storeDB(val):
    #return f'val is: {val}'
    check = checkDBConnection()
    if check:
    return "<p>Database access successful...........</p>"
    # Closing Database Connection
    #cnx.close()
    else:
    return "<p>Connection failed ......</p>"

    Continue reading...

Compartilhe esta Página