i am currently working on a Python project, which sometimes has to write several thousand entries to the DB one after the other. Unfortunately I often get a connection error.
At first I thought that it is because I do not close the DB connection after each query, but then the message comes after the first entry in the DB. Otherwise the error appears after a few hundred entries. What am I doing wrong when I call the DB?
class Database ():
def __init__(self):
pass
def connect(self, log):
try:
self.conn = mysql.connector.connect(host=self.Adress,
port=self.Port,
database=self.Database,
user=self.Username,
password=self.Password)
except Exception as e:
log.bootLog(self, "Database Connection ---- FAILED: " + str(e), "Error")
sys.exit(0)
return
def insert(self, query, args, log):
cursor = self.conn.cursor()
try:
cursor.execute(query, args)
self.conn.commit()
cursor.close()
self.conn.close()
except Exception as e:
log.writeLog(self, "Database Connection ---- FAILED: " + str(e) + "\n" + cursor.statement, "Error")
return
Traceback (most recent call last):
File "/home/tobi/PycharmProjects/TradingBot/Module/brokerAPI.py", line 27, in initialisierung
tradingBot.Database.insert(query,args, tradingBot.log)
File "/home/tobi/PycharmProjects/TradingBot/Module/MySQLConnector.py", line 32, in insert
cursor = self.conn.cursor()
File "/home/tobi/PycharmProjects/TradingBot/venv/lib/python3.7/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.
self.connin theexceptblock too. Or moveself.conn.close()to afinallyblock. Or use the connection as a context manager, if you are using the latestmysql-connector-pythonpackage.__init__) and if you wanted, you could add a__del__method to explicitly close the connection but if yourDatabaseinstance is being garbage collected, then the connection instance would also be garbage collected and closed anyway.