【问题标题】:How are the keys defined in pymysql if we use DictCursor?如果我们使用 DictCursor,pymysql 中的键是如何定义的?
【发布时间】:2019-09-01 06:44:17
【问题描述】:

我一直在寻找一种方法来更好地表示通过 pymysql 在 MySQL 表上运行查询后得到的输出,并偶然发现了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 是否可以由我们自己定义?如果不是,如何选择键的名称。

【问题讨论】:

    标签: python mysql python-3.x pymysql


    【解决方案1】:

    key来自结果集的头部。

    如果您运行命令SHOW TABLES,则无法更改标题。这是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           |
    +---------------+
    

    【讨论】:

      猜你喜欢
      • 2014-06-02
      • 2019-08-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      • 1970-01-01
      • 2023-04-01
      • 2018-09-16
      • 1970-01-01
      相关资源
      最近更新 更多