我正在尝试创建一个简单的脚本来更改一些mysql数据,但我对参数化查询有点困惑。代码如下所示:
reader_id = sys.argv[1]
cmd_id = sys.argv[2]
conn = mysql.connect(user='...', passwd='...', host='...', db='...')
curs = conn.cursor()
mysql_data = {
"reader_id": int(reader_id),
"cmd_id": int(cmd_id)
}
curs.execute("UPDATE `reader_config_hw` SET `changed_` = '1' "
"WHERE `object_id` = %(reader_id)d AND `id` = %(cmd_id)d;", mysql_data)
curs.execute("UPDATE `reader` SET `check_for_command` = '1' WHERE `id` = %(reader_id)d", mysql_data)
,错误结果是
Traceback (most recent call last):
File "./main.py", line 25, in <module>
"WHERE `object_id` = %(reader_id)d AND `id` = %(cmd_id)d;", mysql_data)
File "/usr/lib64/python3.6/site-packages/MySQLdb/cursors.py", line 210, in execute
query = query % args
TypeError: %d format: a number is required, not str
它说这个数字是必需的,但我已经用int(reader_id)
更改了变量的类型,是不是?
答案 0 :(得分:1)
尝试改变
"WHERE 'object_id' = %(reader_id)d AND 'id' = %(cmd_id)d;"
到
"WHERE 'object_id' = %(reader_id)s AND 'id' = %(cmd_id)s;"
我认为变量调用后的'd'表示“数字”,而你需要使用字符串。
编辑:澄清一下,在MySQL查询中可以用字符串代替整数