python中的sql查询不返回任何结果

4si2a6ki  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(499)

我正在使用pymysql处理python中的sql查询。假设我们有以下函数

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'"

它印的是正确的东西。
有什么想法吗?提前谢谢!

gjmwrych

gjmwrych1#

您需要将参数“绑定”到查询:

sql = "select b.text from book b where b.id = %s"
cursor.execute(sql, (bid, ))

注意:使用占位符的好处( %s )在查询中,并向 execute() 通常为您处理所有不同的变量类型(int、str、dates等等)。
看看你可以传递给哪些对象的文档 execute() .

3gtaxfhh

3gtaxfhh2#

“123”参数没有修改用于sql查询的字符串。更改为:

sql = "select b.text from book b where b.id = '{}'".format(bid)

相关问题