我使用MYSQL(版本5.5.31-0 + wheezy1)和python(版本2.7.3),声明如下:
q ="""INSERT INTO scale_equipment truck_id, product_id, driver_id, field_id, pit_id, harvest_equipment_id, weight, status VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""",(truck_id, product_id, driver_id, field_id, pit_id, harvest_equipment_id, 0, status)
如果我使用:
q ="""INSERT INTO scale_equipment truck_id, product_id, driver_id, field_id, pit_id, harvest_equipment_id, weight, status VALUES ('002', 'CS', 'BG', 'HD1', 'T1', 'C1', 0, 'U')"""
它运行正常,我在SQL语句中传递变量我做错了什么
我在使用变量点击执行查询语句之前打印出q,这就是它的样子:
'INSERT INTO scale_equipment truck_id, product_id, driver_id, field_id, pit_id, harvest_equipment_id, weight, status VALUES (%s, %s, %s, %s, %s, %s, %s, %s)', ('002', 'CS', 'BG', 'HD1', 'T1', 'C1', 0, 'U')
非常感谢任何帮助。
答案 0 :(得分:1)
查询参数应必须在execute()
的第二个参数中传递:
params = ('002', 'CS', 'BG', 'HD1', 'T1', 'C1', 0, 'U')
cursor.execute("""INSERT INTO
scale_equipment
(truck_id, product_id, driver_id, field_id, pit_id, harvest_equipment_id, weight, status)
VALUES
(%s, %s, %s, %s, %s, %s, %s, %s)""", params)
在这种情况下你不会担心sql注入,mysqldb驱动程序会为你逃避。