python-mysqlHow can I keep my MySQL connection alive when using Python?
The MySQL connection can be kept alive when using Python by setting the connection timeout of the connection object. This can be done by setting the connect_timeout
parameter to a non-zero value.
For example,
import mysql.connector
db = mysql.connector.connect(
host="localhost",
user="user",
passwd="passwd",
connect_timeout=60
)
print(db)
Output example
<mysql.connector.connection_cext.CMySQLConnection object at 0x7f1b8e1b2fd0>
The above code will create a connection object db
and set the connection timeout to 60 seconds. This ensures that the connection will stay alive for 60 seconds even if there is no activity on the connection.
Code explanation
import mysql.connector
: This imports the mysql.connector module.db = mysql.connector.connect(host="localhost", user="user", passwd="passwd", connect_timeout=60)
: This creates a connection objectdb
and sets the connection timeout to 60 seconds.print(db)
: This prints the connection objectdb
.
Helpful links
More of Python Mysql
- How can I connect Python to a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How can I use Yum to install the MySQLdb Python module?
- How do I check the version of MySQL I am using with Python?
- How can I retrieve unread results from a MySQL database using Python?
- How can I use Python to insert a timestamp into a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How do I use Python to connect to a MySQL database using XAMPP?
- How do I connect to a MySQL database using XAMPP and Python?
- How do I update values in a MySQL database using Python?
See more codes...