如何将光标变为预准备语句和字典。 我有以下内容。
cursor(cursor_class = MySQLCursorPrepared)
prints <class 'mysql.connector.cursor.MySQLCursorPrepared'>
cursor(dictionary = True)
prints <class 'mysql.connector.cursor.MySQLCursorDict'>
所以我用字典覆盖准备好的语句。我正在使用python3的mysql连接器。
我试过了
cursor(prepared=True,dictionary=True)
错误
Cursor not available with given criteria: dictionary, prepared
有趣的是
cursor(cursor_class = MySQLCursorPrepared,dictionary = True)
我没有错误,但数据不是字典类型。
答案 0 :(得分:3)
答案 1 :(得分:2)
用行值压缩cursor.column_names
是一个很好的解决方法:
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'])
有关MySQLCursor.column_names
的文档,请参见https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-column-names.html。
答案 2 :(得分:0)
这个天真的解决方法似乎对我有用-如果我禁用SSL,我可以在“ strace”输出中看到多个相同的查询仅发送到服务器一次,并且当我遍历游标的行时,我肯定会返回字典:
from mysql.connector.cursor import MySQLCursorDict, MySQLCursorPrepared
class PreparedDictionaryCursor(MySQLCursorDict, MySQLCursorPrepared):
pass