Search code examples
pythonmysqlpython-3.xpymysql

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


I was looking for a way to better represent the output we get after running a query on a MySQL table via pymysql and stumbled upon DictCursor.
I gave it a shot and was able to achieve the following

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)

I get an output as follows

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

I was wondering if the key Tables_in_db_name is something we can define ourselves? If not how are the name of the keys picked.


Solution

  • The key comes from the header of the result set.

    You can't change the header if you run the command SHOW TABLES. Here's an example of this command in the mysql client:

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

    If you want more control, you can query the INFORMATION_SCHEMA (which is exactly what SHOW TABLES actually does internally):

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