1

我正在使用带有以下语句的 MYSQL (ver. 5.5.31-0+wheezy1) 和 python (ver. 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')

任何帮助将不胜感激。

4

1 回答 1

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 驱动程序会为您转义。

于 2013-09-16T17:43:14.513 回答