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 connect Python to a MySQL database?
- How can I use Python to retrieve data from MySQL?
- How can I connect Python and MySQL?
- How can I use Python to interact with a MySQL database using YAML?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I connect to a MySQL database over SSH using Python?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database using an Xserver?
See more codes...