版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sun_ashe/article/details/83828078
Python连接MySQL获取当前链接的processlist id
在使用MySQL client API连接数据库时,返回的MySQL链接句柄中有当前链接的processlist id,如果是使用python 该怎么获取呢?
百度了一番,发现没人在乎这个问题,可能别人没有涉及到这里。
一、解决方法
python程序一般使用pymysql连接MySQL数据库,如下
import pymysql
# 1. 连接数据库后返回但是一个连接对象,有这个连接对象,就可以对数据库进行操作
conn = pymysql.connect(
host = "127.0.0.1", # 数据库的ip地址
port = "3306", # 数据库的端口号
user = "root", # 登陆数据库的用户名
passwd = "123456", # 登陆数据库的密码
db = "lesson54" # 要连接的数据库,必须提前创建好,否则会连接出错
)
然后就可以拿这个conn去执行一系列的操作。但是如何拿到此链接在MySQL中的processlist id 呢。只好去github上面看下pymysql的代码,看下pymysql.connect返回的对象是什么样子的,包含了哪些可用的函数。
由于没写过python程序,以下见解如果有问题,请指正
pymysql包中包含了一个connection类,这个类负责处理各种请求。在
PyMySQL/pymysql/connections.py
conn=pymysql.connect 在PyMySQL/pymysql/__init__.py
中
代码如下
def Connect(*args, **kwargs):
"""
Connect to the database; see connections.Connection.__init__() for
more information.
"""
from .connections import Connection
return Connection(*args, **kwargs)
返回的就是Connection的一个实例。
而类Connection中包含了很多可共用户使用的函数,其中就有
def thread_id(self):
return self.server_thread_id[0]
问题解决,测试之。
二、验证
python代码如下
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pymysql
# 1. 连接数据库后返回但是一个连接对象,有这个连接对象,就可以对数据库进行操作
conn = pymysql.connect(
host = "127.0.0.1", # 数据库的ip地址
port = 13307, # 数据库的端口号
user = "ashe", # 登陆数据库的用户名
passwd = "ashe", # 登陆数据库的密码
db = "ashe" # 要连接的数据库,必须提前创建好,否则会连接出错
)
cursor = conn.cursor();
print(conn.thread_id())
发现没有问题。
ashe@ubuntu:/data/test$ python ./test.py
21
最后吐槽一下,pymysql的文档很差劲https://pymysql.readthedocs.io/en/latest/modules/connections.html#module-pymysql.connections