Mysql.connector.errors.operationalerror mysql connection not available

I'm using Flask-SQLAlchemy 1.0, Flask 0.10, SQLAlchemy 0.8.2, and Python 2.7.5. I'm connecting to MySQL 5.6 with Oracle's MySQL Connector/Python 1.0.12.

When I restart my web server (either Apache2 or Flask's built-in), I receive the exception OperationalError: MySQL Connection not available after MySQL's wait_timeout expires (default 8 hours).

I've found people with similar problems and explicitly set SQLALCHEMY_POOL_RECYCLE = 7200, even though that's Flask-SQLAlchemy's default. When I put a breakpoint here, I see that the teardown function is successfully calling session.remove() after each request. Any ideas?

Update 7/21/2014:

Since this question continues to receive attention, I must add that I did try some of the proposals. Two of my attempts looked like the following:

First:


@contextmanager
def safe_commit():
try:
yield
db.session.commit()
except:
db.session.rollback()
raise

This allowed me to wrap my commit calls like so:


with safe_commit():
model = Model(prop=value)
db.session.add(model)

I am 99% certain that I did not miss any db.session.commit calls with this method and I still had problems.

Second:


def managed_session():
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
try:
response = f(*args, **kwargs)
db.session.commit()
return response
except:
db.session.rollback()
raise
finally:
db.session.close()
return decorated_function
return decorator

To further ensure I wasn't missing any commit calls, I made a Flask wrapper that enabled code such as (if I remember correctly):


@managed_session()
def hello(self):
model = Model(prop=value)
db.session.add(model)
return render_template(...

Unfortunately, neither method worked. I also recall trying to issue SELECT(1) calls in an attempt to re-establish the connection, but I don't have that code anymore.

To me, the bottom line is MySQL/SQL Alchemy has issues. When I migrated to Postgres, I didn't have to worry about my commits. Everything just worked.


Therefore, this code was closing my connection immediately:

def mysql_get_mydb():
   ''
'Takes no args, and returns a connection to MYDB via MYSQL.'
''

creds = fixed_data.MYSQL_ENDPOINTS

try:
cnx = connector.connect(user = 'MYDB',
   password = 'open_sesame',
   host = creds['prod']['MYDB'][0],
   port = 3306,
   database = 'MYDB')
except connector.Error as err:
   if err.errno == connector.errorcode.ER_ACCESS_DENIED_ERROR:
   print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DV_ERROR:
   print("Database does not exist")
else :
   print(err)
# the
else will happen
if there was no error!
   else :
      cnx.close()

return cnx

A more elegant solution than yours:

import requests
import time
import csv
import ast
import sys
import mysql.connector

config = {
   'user': 'root',
   'password': 'password',
   'host': '127.0.0.1',
   'port': '3306',
   'database': 'dbname',
   'raise_on_warnings': True,
}

cnx = mysql.connector.connect( ** config)
cursor = cnx.cursor()

dont make seprate dictionary as "config" just put it inside the cnx statement(it will work for the python 3):

cnx = mysql.connector.connect('user': 'root',
   'password': 'password',
   'host': '127.0.0.1',
   'port': '3306',
   'database': 'dbname',
   'raise_on_warnings': True)


I just take the default code and I run a simple execute command from mysql.connector. However I get the error in the title and I'm not sure what I am doing wrong. Here is the full error message:,Again, in my actual code, I do not have the fill in the blanks in the sshtunnel and connection parts left as default. Any help would be appreciated.,Are you able to connect to the PythonAnywhere account using ssh and the same set of credentials?,...indented so that it was within the "with" block? If not, that would be the problem -- the SSH tunnel through to the MySQL server is closed when you exit that block.

import mysql.connector
import sshtunnel

sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

with sshtunnel.SSHTunnelForwarder(
      ('your SSH hostname'),
      ssh_username = 'your PythonAnywhere username', ssh_password = 'the password you use to log in to the PythonAnywhere website',
      remote_bind_address = ('your PythonAnywhere database hostname, eg. yourusername.mysql.pythonanywhere-services.com', 3306)
   ) as tunnel:
   connection = mysql.connector.connect(
      user = 'your PythonAnywhere username', password = 'your PythonAnywhere database password',
      host = '127.0.0.1', port = tunnel.local_bind_port,
      database = 'your database name, eg yourusername$mydatabase',
   )
cursor = connection.cursor()
cursor.execute("select * from semesters")

for i in cursor:
   print(i)

connection.close()

Traceback (most recent call last):
File "C:\Users\Jaden\python_datebase\database_connect.py", line 17, in <module>
   cursor = connection.cursor()
   File "E:\Python 3.9\lib\site-packages\mysql\connector\connection.py", line 809, in cursor
   raise errors.OperationalError("MySQL Connection not available.")
   mysql.connector.errors.OperationalError: MySQL Connection not available.

cursor = connection.cursor()


The connect() constructor creates a connection to the MySQL server and returns a MySQLConnection object. , The following example shows how to connect to the MySQL server: , It is also possible to create connection objects using the connection.MySQLConnection() class: , Both forms (either using the connect() constructor or the class directly) are valid and functionally equal, but using connect() is preferred and used by most examples in this manual.

The following example shows how to connect to the MySQL server:

import mysql.connector

cnx = mysql.connector.connect(user = 'scott', password = 'password',
   host = '127.0.0.1',
   database = 'employees')
cnx.close()

from mysql.connector import(connection)

cnx = connection.MySQLConnection(user = 'scott', password = 'password',
   host = '127.0.0.1',
   database = 'employees')
cnx.close()

To handle connection errors, use the try statement and catch all errors using the errors.Error exception:

import mysql.connector
from mysql.connector
import errorcode

try:
cnx = mysql.connector.connect(user = 'scott',
   database = 'employ')
except mysql.connector.Error as err:
   if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
   print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
   print("Database does not exist")
else :
   print(err)
else :
   cnx.close()


Initializing the exception supports a few optional arguments, namely msg, errno, values and sqlstate. All of them are optional and default to None. errors.Error is internally used by Connector/Python to raise MySQL client and server errors and should not be used by your application to raise exceptions. , The example which uses error number 1146 is used when Connector/Python receives an error packet from the MySQL Server. The information is parsed and passed to the Error exception as shown. , This exception is the base class for all other exceptions in the errors module. It can be used to catch all errors in a single except statement. , Each exception subclassing from Error can be initialized using the previously mentioned arguments. Additionally, each instance has the attributes errno, msg and sqlstate which can be used in your code.

The following example shows how we could catch syntax errors:

import mysql.connector

try:
cnx = mysql.connector.connect(user = 'scott', database = 'employees')
cursor = cnx.cursor()
cursor.execute("SELECT * FORM employees") # Syntax error in query
cnx.close()
except mysql.connector.Error as err:
   print("Something went wrong: {}".format(err))

The following examples show the result when using no arguments or a combination of the arguments:

>>> from mysql.connector.errors
import Error
   >>>
   str(Error())
'Unknown error'

>>>
str(Error("Oops! There was an error."))
'Oops! There was an error.'

>>>
str(Error(errno = 2006))
'2006: MySQL server has gone away'

>>>
str(Error(errno = 2002, values = ('/tmp/mysql.sock', 2)))
"2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)"

>>>
str(Error(errno = 1146, sqlstate = '42S02', msg = "Table 'test.spam' doesn't exist"))
"1146 (42S02): Table 'test.spam' doesn't exist"

The following example shows how to handle errors when dropping a table which does not exist (when the DROP TABLE statement does not include a IF EXISTS clause):

import mysql.connector
from mysql.connector
import errorcode

cnx = mysql.connector.connect(user = 'scott', database = 'test')
cursor = cnx.cursor()
try:
cursor.execute("DROP TABLE spam")
except mysql.connector.Error as err:
   if err.errno == errorcode.ER_BAD_TABLE_ERROR:
   print("Creating table spam")
else :
   raise


4 days ago This exception is raised for errors which are related to MySQL's operations. For example: too many connections; a host name could not be resolved; bad handshake; server is shutting down, communication errors. , This exception is raised for errors which are related to MySQL's operations. For example: too many connections; a host name could not be resolved; bad handshake; server is shutting down, communication errors. errors.OperationalError is a subclass of errors.DatabaseError . , MySQL Connector/Python Developer Guide / ... / This exception is raised for errors which are related to MySQL's operations. For example: too many connections; a host name could not be resolved; bad handshake; server is shutting down, communication errors. , 1 week ago Dec 17, 2014  ยท OperationalError: MySQL Connection not available. Does anyone know how to fix this? Other forums have had similar errors and fixed the problem by not having too many cursors open, but this is the first call to cursor() , so I'm not sure why it's unavailable.

@contextmanager def safe_commit(): try: yield db.session.commit() except: db.session.rollback() raise

@contextmanager def safe_commit(): try: yield db.session.commit() except: db.session.rollback() raise

with safe_commit(): model = Model(prop = value) db.session.add(model)

def managed_session(): def decorator(f): @wraps(f) def decorated_function( * args, ** kwargs): try: response = f( * args, ** kwargs) db.session.commit() return response except: db.session.rollback() raise
finally: db.session.close() return decorated_functionreturn decorator

@managed_session() def hello(self): model = Model(prop = value) db.session.add(model) return render_template(...

class DoSomething(MethodView): def get(self): try: # do stuff db.session.commit() return flask.render_template('sometemplate.html') except: db.session.rollback() raise app.add_url_rule('/someurl', view_func = DoSomething.as_view('dosomething'), methods = ['GET'])


What is OperationalError?

Operational Error means the unintentional, accidental, negligent act, error or omission in entering or modifying data (including the damage or deletion thereof), or in creating, handling, developing, modifying, or maintaining the data, or in the ongoing operation or maintenance of your computer system.

How do I fix MySQL not connected?

ipconfig and then just check the IP address and put it in place of localhost in the previous command. If this still doesn't works then put 127.0. 0.1:3306 . After this, it will prompt to add or save the password , enter a unique password there.

How do I connect to MySQL connector?

Type the command for the package you want to install:.
To install the mysqlclient package, type the following command: Copy pip install mysqlclient..
To install the mysql-connector-python package, type the following command: Copy pip install mysql-connector-python..
To install the pymysql package, type the following command:.

What does MySQL connector Connect do?

connect() Method. This method sets up a connection, establishing a session with the MySQL server. If no arguments are given, it uses the already configured or default values.