[英]Sql query in Python returns nothing
我正在使用 PyMySQL 处理 python 中的 sql 查询。 假设我们有以下 function
def f(bid)
con=connection()
cursor=con.cursor
sql = "select b.text from book b where b.id = 'bid'"
cursor.execute(sql)
book_text = cursor.fetchone()
print (book_text)
当我做:
f('123abc')
它打印:
()
但是,如果我将上述 sql 查询替换为:
"select b.text from book b where b.id = '123abc'"
它打印正确的东西。
有任何想法吗? 提前致谢!
您需要将参数“绑定”到查询:
sql = "select b.text from book b where b.id = %s"
cursor.execute(sql, (bid, ))
注意:在查询中使用占位符 ( %s
) 并将额外的 object 传递给execute()
的好处通常可以为您处理所有不同的变量类型(int、str、dates、...)。
查看文档,您可以将哪些对象传递给execute()
。
您的 '123abc' 参数没有修改您用于 sql 查询的字符串。 改成:
sql = "select b.text from book b where b.id = '{}'".format(bid)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.