如果我们使用 DictCursor,pymysql 中的键是如何定义的?

How are the keys defined in pymysql if we use DictCursor?

我一直在寻找一种方法来更好地表示我们在 运行 通过 pymysql 查询 MySQL table 之后得到的输出,然后偶然发现了 DictCursor
我试了一下,能够实现以下目标

import pymysql

# Connect to mysql database
conn = pymysql.connect('db_conn_str', 'user_r',
                       'pwd_r', 'db_name')

# Run a query to list all tables in database
cur = conn.cursor(pymysql.cursors.DictCursor)
cur.execute('show tables')
tables = cur.fetchall()

# We get a list of dictionaries
print(tables)

我得到如下输出

[
    {'Tables_in_db_name': 'table_x'}, 
    {'Tables_in_db_name': 'table_y'}, 
    {'Tables_in_db_name': 'table_z'}
]

我想知道密钥 Tables_in_db_name 是不是我们可以自己定义的东西?如果不是,如何选择键的名称。

key来自结果集的header

如果您 运行 命令 SHOW TABLES,则无法更改 header。这是 mysql 客户端中此命令的示例:

mysql> show tables from test;
+----------------+
| Tables_in_test |
+----------------+
| bar            |
| foo            |
+----------------+

如果你想要更多的控制,你可以查询 INFORMATION_SCHEMA(这正是 SHOW TABLES 在内部所做的):

mysql> select table_name as `my_custom_key` from information_schema.tables 
  where table_schema='test';
+---------------+
| my_custom_key |
+---------------+
| bar           |
| foo           |
+---------------+