如果使用PyMySQL,常见的方法如下
connection = pymysql.connect(
host="localhost",
port=3306,
database="forest",
user="root",
password="123456"
)
with connection.cursor() as cursor:
print(cursor)
cursor.execute("select count(*) from user")
data = cursor.fetchall()
print(data,)
其中名词的解释如下:
Connection
Representation of a socket with a mysql server.
The proper way to get an instance of this class is to call connect().Establish a connection to the MySQL databaseCursor
This is the object used to interact with the database.
Do not create an instance of a Cursor yourself. Call connections.Connection.cursor().
2. 连接池用法
连接池指的是应用和数据库的连接池,理论上是应用提前准备好(如启动时)几个和数据库连接好的连接,一直供应用使用,直到应用关闭,省去每次查询时重新连接上数据库和关闭数据库连接的时间。
其中连接池指的即是多个 connection的连接池
具体实践可以使用 DBUtils和 PyMySQL构造连接池
2.1 如何查询到连接池DBUtils User’s Guide, https://webwareforpython.github.io/DBUtils/main.htmlhttps://github.com/WebwareForPython/DBUtils
连接上MySQL,通过命令show full processlist即可查询当前连接上MySQL的连接(或即socket连接)
如下,即为通过 Navicat for MySQL 连接上查询出的结果
通过 DBUtils和 PyMySQL构造连接池的代码如下
import time
import pymysql
from dbutils.pooled_db import PooledDB
pool = PooledDB(pymysql,
3, # 默认初始化好3个连接
host="localhost",
port=3306,
database="forest",
user="root",
password="123456")
connection = pool.connection()
if __name__ == '__main__':
print("sleep 30 ...")
time.sleep(30)
在 Navicat for MySQL 连接上查询出的结果如下(在sleep结束之前),可以看到time=3,即该连接活跃的时间长度



