jim99 jim99 - 6 months ago 47
MySQL Question

Flask-MySQLdb raises _mysql_exceptions.ProgrammingError: closing a closed connection

I'm trying to use Flask-MySQLdb. Every time I go to a page I get the error

_mysql_exceptions.ProgrammingError: closing a closed connection
. Why isn't this working?

from flask import Flask, render_template, request, json
from flask_mysqldb import MySQL

application = Flask(__name__)
mysql = MySQL(application)

application.config['MYSQL_USER'] = 'root'
application.config['MYSQL_PASSWORD'] = 'password'
application.config['MYSQL_DB'] = 'db name'
application.config['MYSQL_HOST'] = 'localhost'

def index():
cur = mysql.connection.cursor()
cur.execute("SHOW TABLES")
rv= cur.fetchall()
return str(rv)

if __name__ == "__main__":


You've initialize the extension on the same application twice. Each time it's initialized, it registers a function that closes the connection. So the second function closes a connection that was already closed by the first registered function. Either remove application from MySQL (preferable) or remove the explicit call to mysql.init_app.

mysql = MySQL()