Python - MySQL 数据库参数化查询
Python - MySQLdb parametrized query
我正在尝试创建一个简单的脚本来更改一些 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)
更改了变量的类型,对吗?
尝试改变
"WHERE 'object_id' = %(reader_id)d AND 'id' = %(cmd_id)d;"
到
"WHERE 'object_id' = %(reader_id)s AND 'id' = %(cmd_id)s;"
我认为变量调用后的 'd' 表示 "digit" 而您需要使用字符串。
编辑:澄清一下,在MySQL查询
中可以使用字符串代替整数
我正在尝试创建一个简单的脚本来更改一些 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)
更改了变量的类型,对吗?
尝试改变
"WHERE 'object_id' = %(reader_id)d AND 'id' = %(cmd_id)d;"
到
"WHERE 'object_id' = %(reader_id)s AND 'id' = %(cmd_id)s;"
我认为变量调用后的 'd' 表示 "digit" 而您需要使用字符串。
编辑:澄清一下,在MySQL查询
中可以使用字符串代替整数