如何使用 Python 将变量传递给 MYSQL [英] How to pass variables to MYSQL using Python
本文介绍了如何使用 Python 将变量传递给 MYSQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 MYSQL(版本 5.5.31-0+wheezy1)和 python(版本 2.7.3)和以下语句:
I am using MYSQL (ver. 5.5.31-0+wheezy1) and python (ver. 2.7.3) with the following statement:
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 语句中传递变量做错了什么
it works fine, what I am I doing wrong to pass the variables in the SQL statement
我在使用变量执行查询语句之前打印出 q,它是这样的:
I print out the q before it hits the execute query statement using the variables and this is what it looks like:
'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')
任何帮助将不胜感激.
推荐答案
查询参数should必须传入execute()
的第二个参数:
Query parameters should must be passed in the second argument of 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 驱动程序会为您进行转义.
In this case you wouldn't worry about sql injections, mysqldb driver does escaping for you.
这篇关于如何使用 Python 将变量传递给 MYSQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文