我想使用sqlalchemy模块将一些数据插入数据库。但是,当我尝试使用它时,会在TypeError: not all arguments converted during bytes formatting
中的query = query % args
字符串上给我错误MySQLdb\cursors.py
。我尝试使用pymysql而不是mysqldb,它给出了相同的错误。
这是代码:
myquery = "INSERT INTO some(id, name, info, det_info, class, cluster, logo) VALUES (?, ?, ?, ?, ?, ?, ?)"
for row in result:
connection1.execute(myquery, (None, row['name'], row['info'], row['det_info'], row['class'], row['cluster'], row['logo']))
我尝试了不同的发送参数变体:带方和不带方,都给出相同的结果。我试图将这些字符串添加到cursors.py:
print(query)
print('----@@@@----@@@@----@@@@----@@@@----@@@@----@@@@----@@@@----')
print(args)
它给出了这个:
b'INSERT INTO some(id, name, info, det_info, class, cluster, logo) VALUES (?, ?, ?, ?, ?, ?, ?)'
还有这个:
(b'NULL', b"'\xd0\xb8\xd0\xbd\xd1\x81\xd1\x82\xd0\xb8\xd1\x82\xd1\x83\xd1\x82'", b"'\xd0\x98\xd0\xbd\'", b"'Institute'", b"'Inte'", b"'\xd0\xa1\xd0\xbe'", b"'1.png'")
因此,我猜测问题可能出在“(?,?,...)”中,并且%操作期间参数将如何改变问题。但是我不知道我是否正确以及如何解决该问题。
如对该问题的评论中所述,Python DB-API的不同实现可以选择使用不同的paramstyle。例如,您选择的工具似乎实现了“格式”参数样式(%s
),但是您试图使用“ qmark”(?
)样式。
但是,由于您已经为SQLAlchemy标记了此问题,请考虑使用SQLAlchemy使用其自己的paramstyle(“命名”)来处理查询,并让SQLAlchemy负责将其转换为DB-API层的本机样式。这样,无论您碰到哪个后端,您的参数查询都将始终看起来相同(并具有命名参数的便利启动)。
import sqlalchemy as sa
# ...
query = sa.text("INSERT INTO student (lastname, firstname) VALUES (:ln, :fn)")
values = {'ln': 'Thompson', 'fn': 'Gord'}
engine.execute(query, values)