I tried to push and run a python program to connect to MySQL using Heroku's ClearDB, but I couldn't connect with the message ʻerror 2055 Lost connection ~`.
As a result, it was not an error related to MySQL, but the way the program was written, but I would like to summarize it for those who are suffering from the same point.
--How to set ClearDB --Detailed operation method of MySQL
At first, after adding ClearDB, I thought that some settings were necessary, so I investigated various things and tried migration and so on. However, I was able to connect to ClearDB itself, and even if I ran the program that operates by connecting to the database alone, no error occurred, and I could not understand the cause.
At that time, I found this article and read it somehow, but as a cause of SQL operation failure ** When executing a query after disconnecting ** Was written. I took it for granted and tried to go next, but suddenly I looked at my code and found that this was the cause.
Because my code was made like this:
main.py
#Module import
#Import program for database operations
import database
#Main processing
#Function call in database
database.get_data()
database.py
import mysql.connector
#Set the connection destination and connect
def get_data():
#Execute query
connection.commit()
connection.close()
Based on this, if you take a look at this article, the code written outside the function will be executed when database
is imported. ..
In other words, the import database
of main.py
will connect to SQL once, but the get_data ()
function of database.py
is not executed because it is only defined, and the lastconnection The flow is that the connection is closed with .close ()
.
After that, when I called the function with database.get_data ()
in main.py
, the connection was already disconnected, so of course the query could not be executed and an error occurred.
Even if you execute only database.py
, it is understandable that no error occurs because it just disconnects the connection without doing anything after connecting.
So I modified the code as below and tried to disconnect by calling the function, and I was able to connect without any error.
main.py
#Module import
#Import program for database operations
import database
#Main processing
#Function call in database
database.get_data()
#add to
database.close_db()
database.py
import mysql.connector
#Set the connection destination and connect
def get_data():
#Execute query
#Fix
def close_db()
connection.commit()
connection.close()
-Case where commit () fails in mysql-connector-python -Run other .py programs in python
Recommended Posts