PyMySQL Query returns bizarre dictionary

Musil Mark :

Problem

I'm using PyMYSQL to query a database using the following SQL translater function.

def retrieve_column(lotkey, column="active",print = False):
    result = None
    try:
        connection = sql_connect()
        with connection.cursor() as cursor:
            # Create a new record
            sql = "SELECT %s FROM table_n"
            val = (column)
            os_print(sql + '\r\n...', end='', style='dim', flush=True)
            cursor.execute(sql, val)
            result = cursor.fetchall()
            connection.close()
    except Exception as e:
        os_print(e, style='error')
        os_print("ERROR: Can't connect to database!", style='error', tts='error')
    return result

Which I call and print using the following lines. Note: The 'active' column is boolean.

active_col = retrieve_column(key)
print(active_col)

Which prints the following bizarre result. It seems to be a dictionary with no values present therein.

...[{'active': 'active'}, {'active': 'active'}, {'active': 'active'}, {'active': 'active'}, {'active': 'active'}, {'active': 'active'}, {'active': 'active'}]

Attempted Solutions

My first step was to run the same query in MySQL workbench which produced the following result.

Workbench Query Which is roughly what I am trying to replicate in Python (Getting a dictionary with each row's boolean value).

Next, I used the python debugger and found that indeed the returned values from cursor.fetchall() are empty dictionaries with nothing but a single key and no values.

Has anyone encountered something similar before?

F.Igor :

Actually using these three instructions:

sql = "SELECT %s FROM table_n"
val = (column)
cursor.execute(sql, val)

You will get the following query executed:

SELECT 'column' FROM table_n

The result is a list of 'column' values (name of the column is also 'column'). Because the parameters of the cursor.execute() method are not literals, but parameter values (in this case, a string value 'column')

If you are trying to select the column value, you need to format the SQL query content, not the paramaters:

sql = "SELECT {colname} FROM table_n"
sql.format( colname = column )
cursor.execute(sql)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=195146&siteId=1