Python連線MySQL獲取當前連結的processlist id
阿新 • • 發佈:2018-11-21
文章目錄
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())
發現沒有問題。
[email protected]:/data/test$ python ./test.py
21
最後吐槽一下,pymysql的文件很差勁https://pymysql.readthedocs.io/en/latest/modules/connections.html#module-pymysql.connections