Python使用pymysql小技巧
在使用pymysql的時候,通過fetchall()或fetchone()可以獲得查詢結(jié)果,但這個返回數(shù)據(jù)是不包含字段信息的(不如php方便)。查閱pymysql源代碼后,其實獲取查詢結(jié)果源代碼也是非常簡單的,直接調(diào)用cursor.description即可。
譬如:
db = pymysql.connect(...) cur = db.cursor() cur.execute(sql) print(cur.description) result = cur.fetchall() data_dict=[] for field in cur.description: data_dict.append(field[0]) print(data_dict)
在pymysql的 pymysql/cursors.py 中,找到 class Cursor 可以看到如下代碼:
def __init__(self, connection): self.connection = connection self.description = None self.rownumber = 0 self.rowcount = -1 self.arraysize = 1 self._executed = None self._result = None self._rows = None self._warnings_handled = False
因此,調(diào)用 cur.rowcount 是可以迅速返回查詢結(jié)果記錄數(shù)的,不需要通過 len() 獲得。
- Python中操作mysql的pymysql模塊詳解
- Python MySQL數(shù)據(jù)庫連接池組件pymysqlpool詳解
- Python中模塊pymysql查詢結(jié)果后如何獲取字段列表
- python使用pymysql實現(xiàn)操作mysql
- 詳解使用pymysql在python中對mysql的增刪改查操作(綜合)
- Python 3.x 連接數(shù)據(jù)庫示例(pymysql 方式)
- Python使用pymysql從MySQL數(shù)據(jù)庫中讀出數(shù)據(jù)的方法
- python 3.6 +pyMysql 操作mysql數(shù)據(jù)庫(實例講解)
- Python3連接MySQL(pymysql)模擬轉(zhuǎn)賬實現(xiàn)代碼
- python3.6使用pymysql連接Mysql數(shù)據(jù)庫
- python和mysql交互操作實例詳解【基于pymysql庫】
相關(guān)文章
使用python將大量數(shù)據(jù)導(dǎo)出到Excel中的小技巧分享
今天小編就為大家分享一篇使用python將大量數(shù)據(jù)導(dǎo)出到Excel中的小技巧心得,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
對pandas的算術(shù)運算和數(shù)據(jù)對齊實例詳解
今天小編就為大家分享一篇對pandas的算術(shù)運算和數(shù)據(jù)對齊實例詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12

