Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python MySql Connector prepared statement and dictionary class

How do I make my cursor a prepared statement as well as a dictionary. I have the following.

 cursor(cursor_class = MySQLCursorPrepared)
 prints <class 'mysql.connector.cursor.MySQLCursorPrepared'>
 cursor(dictionary = True)
 prints <class 'mysql.connector.cursor.MySQLCursorDict'>

So I am overwriting the prepared statement with the dictionary. I am using the mysql connector for python3.

I have tried

 cursor(prepared=True,dictionary=True)

That errors with

Cursor not available with given criteria: dictionary, prepared

Interestingly

cursor(cursor_class = MySQLCursorPrepared,dictionary = True)

I get no errors but the data not of dictionary type.

like image 876
user3525290 Avatar asked Dec 23 '22 08:12

user3525290


2 Answers

I have the same problem. Prepared and Dictionary don't work together.

I reported bug: https://bugs.mysql.com/bug.php?id=92700

Now we wait ;)

like image 192
SaleCar Avatar answered Dec 29 '22 01:12

SaleCar


Zipping cursor.column_names with the row values is a good workaround:

cursor = connection.cursor(prepared=True)
query = 'SELECT foo, bar FROM some_table WHERE a = %s AND b = %s'
a = 1
b = 42
cursor.execute(query, [a, b])
rows = cursor.fetchall()
for row in rows:
    result = dict(zip(cursor.column_names, row))
    print(result['foo'], result['bar'])

See https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-column-names.html for documentation on MySQLCursor.column_names.

like image 36
Webucator Avatar answered Dec 28 '22 23:12

Webucator