我们以查询某个库下所有的表为例。
方式1
先创建数据库连接,然后使用 use dbname 选择数据库。
import pymysql
conn = pymysql.connect(host='127.0.0.1',
user='root',
password='123456',
port=3306)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute('use information_schema;')
cursor.execute('show tables;')
for item in cursor.fetchall():
print(type(item), item)
cursor.close()
conn.close()
运行结果示例(省略部分内容):
<class 'dict'> {'Tables_in_information_schema': 'CHARACTER_SETS'}
<class 'dict'> {'Tables_in_information_schema': 'COLLATIONS'}
<class 'dict'> {'Tables_in_information_schema': 'COLLATION_CHARACTER_SET_APPLICABILITY'}
<class 'dict'> {'Tables_in_information_schema': 'COLUMNS'}
<class 'dict'> {'Tables_in_information_schema': 'COLUMN_PRIVILEGES'}
<class 'dict'> {'Tables_in_information_schema': 'ENGINES'}
<class 'dict'> {'Tables_in_information_schema': 'EVENTS'}
<class 'dict'> {'Tables_in_information_schema': 'FILES'}
<class 'dict'> {'Tables_in_information_schema': 'GLOBAL_STATUS'}
<class 'dict'> {'Tables_in_information_schema': 'GLOBAL_VARIABLES'}
方式2
连接时指定数据库:
import pymysql
conn = pymysql.connect(host='127.0.0.1',
user='root',
password='123456',
port=3306,
database='information_schema') # 指定数据库
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute('show tables;')
for item in cursor.fetchall():
print(type(item), item)
cursor.close()
conn.close()