jim99
jim99

Reputation: 89

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'
mysql.init_app(application)

@application.route('/')
def index():
    cur = mysql.connection.cursor()
    cur.execute("SHOW TABLES")
    rv= cur.fetchall()
    return str(rv)

if __name__ == "__main__":
    application.run()

Upvotes: 1

Views: 500

Answers (1)

davidism
davidism

Reputation: 127180

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()
mysql.init_app(application)

Upvotes: 1

Related Questions