'NoneType' object has no attribute 'cursor'
The error occurs because mysql.connection
is None
. It doesn't matter here what type of object mysql
is.
The Flask-MySQL documentation for MySQL.connection
tells you when that attribute is going to be None
:
Attempts to connect to the MySQL server.
Returns: Bound MySQL connection object if successful or
None
if unsuccessful.
So the attempt to connect to the server could have failed. The extension will open a connection to MySQL once per request; it failed to connect on a separate request from the one that succeeded.
Looking at the source code for the extension I see that it'll also return None
when there is no app context (at which point _app_ctx_stack.top
is None
). You can't use this function outside of a request.
If you do need this outside of a request, you need to manually create an app context first:
with app.app_context(): cur = mysql.connection.cursor()
These errors occur when your DB connection is not established. So please check your DB connection method and properties and then try to execute.