Python 将变量传递到MySQL查询
我试图将一个变量Python 将变量传递到MySQL查询,python,mysql,Python,Mysql,我试图将一个变量loc传递到我的execute语句中,以从我的db中获取一个单独的slug编号,但我不知道如何传递它。我的方法是这样设置的,因为我可能会执行几个不同的查询,并且不需要一堆重复的代码 def query(sql): db = mysql.connector.connect( host="localhost", user="root", passwd="password!", database="db"
loc
传递到我的execute语句中,以从我的db中获取一个单独的slug编号,但我不知道如何传递它。我的方法是这样设置的,因为我可能会执行几个不同的查询,并且不需要一堆重复的代码
def query(sql):
db = mysql.connector.connect(
host="localhost",
user="root",
passwd="password!",
database="db"
)
cursor = db.cursor()
cursor.execute(sql)
final_result = [i[0] for i in cursor.fetchall()]
return final_result
def individual(loc):
sql = "SELECT slug FROM auctions WHERE location = %s", loc
return query(sql)
我通常是这样做的
sql = """SELECT slug FROM auctions WHERE location = %(loc_name)s
"""
cursor.execute(sql, {"loc_name": loc,})
将值作为字典传递。感觉更安全、更整洁:)
如果“有时”你需要所有的弹头,“有时”你需要一个基于位置的特定弹头
if loc: #check if there is loc value
sql = """SELECT slug FROM auctions WHERE location = %(loc_name)s"""
cursor.execute(sql, {"loc_name": loc,})
else:
sql = """SELECT slug FROM auctions"""
cursor.execute(sql)
那会管用的,但感觉有更好的写作风格。。嗯…ref:有时候我需要所有的鼻涕虫,所以位置并不重要。如果我在没有位置的情况下执行,我会得到错误,对吗?我只是根据你的字符串来写。。我将编辑我的答案以涵盖您的评论