python-mysqlHow can I keep a MySQL connection alive in Python?
The following code block can be used to keep a MySQL connection alive in Python:
import mysql.connector
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="passwd"
)
# Create a Cursor object to execute queries
my_cursor = mydb.cursor()
# Keep the connection alive by running a query every 5 minutes
while True:
my_cursor.execute("SELECT 1")
time.sleep(300)
The code above will keep the MySQL connection alive by running a query every 5 minutes. This is done by creating a mysql.connector.connect object, which is used to create a Cursor object. Then, a query is executed in an infinite loop, with a time.sleep() of 5 minutes (300 seconds) between each query.
The parts of this code are:
import mysql.connector: This imports themysql.connectormodule, which is used to connect to the MySQL database.mydb = mysql.connector.connect(): This creates amysql.connector.connectobject, which is used to connect to the MySQL database.my_cursor = mydb.cursor(): This creates aCursorobject, which is used to execute queries on the database.my_cursor.execute("SELECT 1"): This executes a query on the database.time.sleep(300): This pauses the code for 5 minutes (300 seconds).
Helpful links
More of Python Mysql
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How do I connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to create a login system?
- How can I use Python and MySQL to generate a PDF?
- How do I use Python to connect to a MySQL database using XAMPP?
- How do Python and MySQL compare to MariaDB?
- How can I convert data from a MySQL database to XML using Python?
- How do I update a row in a MySQL database using Python?
- How do I set up a secure SSL connection between Python and MySQL?
- How can I use Python to retrieve data from MySQL?
See more codes...