MySQL Connection not available. (mysql + python flask)

Viewed 58

I have a Flask app that connects to MySQL. Here is an example of a page that pulls data from my database and displays it as a webpage, using the template feature in flask.

@app.route("/details", methods=['GET'])
def details():
  mycursor = mydb.cursor()
  
  path = request.args.get('file')
  sql = "SELECT * FROM customers WHERE filepath = %s"
  adr = (path, )

  mycursor.execute(sql, adr)

  myresult = mycursor.fetchall()

  mydb.commit()
  mydb.close() # I added this after reading StackOverflow answers
  try:
    computer_readable_cat = myresult[0][3]
    return render_template("view.html", stuff = myresult, cate = cats[computer_readable_cat], title = myresult[0][1], d = myresult[0][6])
  except:
    return render_template("error.html", custom_message = "Not Found", title = "404", http = "404")

This code gave me a "MySQL Connection not available" error.

I've reviewed all of the other answers and they suggested that I close the SQL connections in my code. I completed this by adding a mydb.close() statement after I committed to the DB. However, the error persisted.

For reference, this is my full error message:

[2022-07-10 00:41:38,461] ERROR in app: Exception on /details [GET]
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 2077, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1525, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1523, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1509, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "index.py", line 118, in details
    mycursor = mydb.cursor()
  File "/usr/local/lib/python3.8/dist-packages/mysql/connector/connection_cext.py", line 590, in cursor
    raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.

I'm using the mysql package, imported as import mysql.connector, and this is my config:

mydb = mysql.connector.connect(
  host="localhost",
  user="dave",
  password="12345",
  database="files"
)

Update: I've done some reading and I've heard that this issue occurs when you don't close the connection to the database. I've tried to fix this my adding the mydb.close() function, but nothing has changed.

0 Answers
Related