jim99 jim99 - 1 year ago 184
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__":

Answer Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download