Python PyMySQL:获取 DB 列表


#Python PyMySQL


方式1:

import pymysql

conn = pymysql.connect(host='127.0.0.1',
                       user='root',
                       password='123456',
                       port=3306)
cursor = conn.cursor()
cursor.execute('show databases;')

for item in cursor.fetchall():
    print(type(item), item)   # item 是 tuple 元组

cursor.close()
conn.close()

运行结果示例:

<class 'tuple'> ('information_schema',)
<class 'tuple'> ('mysql',)
<class 'tuple'> ('performance_schema',)
<class 'tuple'> ('school',)
<class 'tuple'> ('test',)

方式2:

查询结果可以是 dict 类型,不过需要生成 cursor 时指定 cursor 参数为 pymysql.cursors.DictCursor 。

import pymysql

conn = pymysql.connect(host='127.0.0.1',
                       user='root',
                       password='123456',
                       port=3306)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 指定 cursor 后,结果会被处理为 dict
cursor.execute('show databases;')

for item in cursor.fetchall():
    print(type(item), item)

cursor.close()
conn.close()

运行结果示例:

<class 'dict'> {'Database': 'information_schema'}
<class 'dict'> {'Database': 'mysql'}
<class 'dict'> {'Database': 'performance_schema'}
<class 'dict'> {'Database': 'school'}
<class 'dict'> {'Database': 'test'}


( 本文完 )