Sql Python 中的查询 returns 无
Sql query in Python returns nothing
我正在使用 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'"
它打印正确的东西。
有什么想法吗?提前致谢!
您的“123abc”参数并未修改您用于 sql 查询的字符串。
更改为:
sql = "select b.text from book b where b.id = '{}'".format(bid)
您需要'bind'查询的参数:
sql = "select b.text from book b where b.id = %s"
cursor.execute(sql, (bid, ))
注意:在查询中使用占位符 (%s
) 并将附加对象传递给 execute()
的好处通常是处理所有不同的变量类型 ( int, str, dates, ...) 给你。
查看 docs 可以传递给 execute()
的对象。
我正在使用 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'"
它打印正确的东西。
有什么想法吗?提前致谢!
您的“123abc”参数并未修改您用于 sql 查询的字符串。 更改为:
sql = "select b.text from book b where b.id = '{}'".format(bid)
您需要'bind'查询的参数:
sql = "select b.text from book b where b.id = %s"
cursor.execute(sql, (bid, ))
注意:在查询中使用占位符 (%s
) 并将附加对象传递给 execute()
的好处通常是处理所有不同的变量类型 ( int, str, dates, ...) 给你。
查看 docs 可以传递给 execute()
的对象。