I am trying to write several dataframes in mysql. I use mysql.connector for the connection and sqlalchemy to create an engine.
Most dataframes are written correctly to the database. Unfortunately the application stops with the following error:
sqlalchemy.exc.DatabaseError: (mysql.connector.errors.DatabaseError) 2006 (HY000): MySQL server has gone away
...
During handling of the above exception, another exception occurred:
...
_mysql_connector.MySQLInterfaceError: MySQL server has gone away
Since the dataframe that breaks the connection is also the largest one (pickle file: 198MB) I assumed that it is due to the MySql-Server setting max_allowed_packet or timeout. (As described here)
So I have extended the config file within my SQLConnector (see below) by 'connect_timeout': 900. Unfortunately without result. I have also read that you should adjust the my.cnf of the MySql server. Unfortunately I did not know exactly where to find them. After a long search I found the following order. C:\Program Files\MySQL\MySQL Server 8.0\etc with the file mysqlrouter.conf.sample. Here I have downloaded a my.cnf file and put it into the folder. Unfortunately without result, because I did not know how to set up MySql so that the server uses this file.
Does anyone know how I can fix this error? Or how I can configure the MySql Server preference settings max_allowed_packet or timeout?
Main:
mysqlConnector = MySQLConnector()
dbConnection = mysqlConnector.init_engine()
for df_tuple in df_all_tuple:
df_name = df_tuple[0]
df = pd.DataFrame(df_tuple[1])
df.to_sql(con=mydb, name=df_name, if_exists='fail', chunksize=20000)
SQLConnector:
import mysql.connector
from mysql.connector import errorcode
import sqlalchemy as db
config = {
'user': 'root',
'password': '',
'host': '127.0.0.1',
'database': 'test',
'raise_on_warnings': True,
'use_pure': False,
'autocommit': True,
'connect_timeout': 900
}
class MySQLConnector:
def __init__(self):
connectTest = self.connect()
print("Connection to database: " + str(connectTest))
def init_engine(self):
try:
connect_string = 'mysql+mysqlconnector://{}:{}@{}/{}?charset=utf8mb4'.format(config.get("user"),
config.get("password"),
config.get("host"),
config.get("database"),
pool_pre_ping=True)
print("Engine: " + connect_string)
sqlengine = db.create_engine(connect_string)
except:
print("SQLConnector: Sqlalchemy error. Can't create engine....")
else:
dbConnection = sqlengine.connect()
return dbConnection
def connect(self):
try:
con = mysql.connector.connect(**config)
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")
if self.createDB() is True:
return self.connect()
elif err.errno == errorcode.CR_SERVER_GONE_ERROR:
print("The client couldn't send a question to the server.")
print("err: " + err)
elif err.errno == errorcode.CR_SERVER_LOST:
print(
"The client didn't get an error when writing to the server, but it didn't get a full answer (or any answer) to the question.")
print("err: " + err)
else:
print(err)
return None
else:
if con.is_connected():
db_Info = con.get_server_info()
print("Connected to MySQL Server version ", db_Info)
sqlcursor = con.cursor()
return con
def createDB(self):
try:
mydb = mysql.connector.connect(
host=config.get("host"),
user=config.get("user"),
passwd=config.get("password")
)
except mysql.connector.Error as err:
print(err)
else:
sqlcursor = mydb.cursor()
try:
sqlcursor.execute('CREATE DATABASE {}'.format(config.get("database")))
except mysql.connector.Error as err:
print(err)
return False
else:
print("Database created!")
return True