#調用self._query方法進行查詢
def execute(self, query, args=None):
"""Execute a query
:param str query: Query to execute.
:param args: parameters used with query. (optional)
:type args: tuple, list or dict
:return: Number of affected rows
:rtype: int
If args is a list or tuple, %s can be used as a placeholder in the query.
If args is a dict, %(name)s can be used as a placeholder in the query.
"""
while self.nextset():
pass
query = self.mogrify(query, args)
result = self._query(query)
self._executed = query
return result
#調用_do_get_result獲取查詢結果
def _query(self, q):
conn = self._get_db()
self._last_executed = q
self._clear_result()
conn.query(q)
self._do_get_result()
return self.rowcount
#這裏獲取結果
def _do_get_result(self):
conn = self._get_db()
self._result = result = conn._result
self.rowcount = result.affected_rows
self.description = result.description
self.lastrowid = result.insert_id
self._rows = result.rows
self._warnings_handled = False
if not self._defer_warnings:
self._show_warnings()
其實看到這裏代碼邏輯已經很清楚了,在調用cursor.execute執行SQL的時候,就將MySQL查詢的結果放到result這個變量裏了,也就是說結果集放到了客戶端的內存變量裏,那麽獲取數據的方式也就是從這個內存變量裏去獲取數據,只是獲取的行為有所不同而已了。
def fetchone(self):
"""Fetch the next row"""
self._check_executed()
if self._rows is None or self.rownumber >= len(self._rows):
return None
result = self._rows[self.rownumber]
self.rownumber += 1
return result
def fetchmany(self, size=None):
"""Fetch several rows"""
self._check_executed()
if self._rows is None:
return ()
end = self.rownumber + (size or self.arraysize)
result = self._rows[self.rownumber:end]
self.rownumber = min(end, len(self._rows))
return result
def fetchall(self):
"""Fetch all the rows"""
self._check_executed()
if self._rows is None:
return ()
if self.rownumber:
result = self._rows[self.rownumber:]
else:
result = self._rows
self.rownumber = len(self._rows)
return result
口說無憑,我們直接通過Wireshark抓包來證明壹下,首先我在本地執行腳本如下,然後我監聽本地的網卡流量
import pymysql
conn = pymysql.connect(host='xxx', port=3306,
user='xucl', password='xuclxucl', database='xucl')
cursor = conn.cursor()
cursor.execute("select * from t")
註意,我這裏並沒有執行fetch操作,如果監聽到的包裏面包含了結果,那麽就證明我們前面的分析是正確的,話不多說開始實驗,Wireshark抓包如下:
果然跟我們之前的預測是壹致的,即使沒有進行fetch操作,MySQL也將結果集發送到客戶端了。另外關於結果集發送,可以參考我另外壹篇文章:《由壹個抓瞎的SQL引申出去》
結論:
客戶端執行SQL的時候,MySQL壹次性將結果集發送給了客戶端
客戶端接收到結果集以後存儲本地內存變量中
fetch結果只是從這個本地變量中獲取,fetchone/fetchmany/fetchall只是獲取行為的不通,因此對於MySQL來說並沒有什麽不通的。