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.connector
module, which is used to connect to the MySQL database.mydb = mysql.connector.connect()
: This creates amysql.connector.connect
object, which is used to connect to the MySQL database.my_cursor = mydb.cursor()
: This creates aCursor
object, 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
- How can I use Python to retrieve data from MySQL?
- How can I use Python and MySQL to create a login system?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How can I host a MySQL database using Python?
- How do I fix a bad MySQL handshake error in Python?
- How can I connect Python to a MySQL database using an Xserver?
- How do I connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python and MySQL?
See more codes...