在python的SQL查询中使用变量 [英] Use a variable in SQL queries in python
问题描述
我的python脚本如下:
My python script looks like this:
#!/usr/bin/python
import MySQLdb
u='ABNCSDS7612'
db = MySQLdb.connect(host="localhost",user="root",passwd="abc",db="mydb")
cur = db.cursor()
sql=("insert into t1(p_id,job_id) Values ((select p_id from t2 where name='OUTPUT'),
(select job_id from job where job_uuid= "%s"))",(u))
cur.execute(*sql)
db.commit()
我在试图插入2列值的地方触发了一条插入语句,并且我想从python脚本 u ='ABNCSDS7612'中的变量获取第二列的值.我从许多类似的职位获得帮助,但没有运气.我仍然面临如下错误:
I am firing an insert statement where I am trying to insert 2 column values, and I want value of 2nd column from a variable in my python script u='ABNCSDS7612' . I took help from a lot of similar posts but no luck. I am still facing the error as below:
SyntaxError: invalid syntax
在sql中%s之后出现的括号后面显示错误.有人可以帮忙吗?
It is showing error after the brackets which occur after %s in sql. Can someone please help?
推荐答案
无效的语法错误是由于您使用引号引起的.
Invalid syntax error is because of the way you've put the quotes.
实际上,您不需要在占位符周围使用引号.并且,您需要将查询参数放入元组.另外,我会在多行上编写查询以提高可读性:
You actually don't need the quotes around the placeholder. And, you need to put your query parameter into a tuple. Also, I would write the query on multiple lines to improve readability:
sql = """
insert into
t1(p_id,job_id)
Values
((select p_id from t2 where name='OUTPUT'),
(select job_id from job where job_uuid = %s))"""
cur.execute(sql, (u, ))
这篇关于在python的SQL查询中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!