【问题标题】:Sql query in Python returns nothingPython中的Sql查询不返回任何内容
【发布时间】:2020-09-25 18:51:39
【问题描述】:

我正在使用 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'"

它打印出正确的东西。

有什么想法吗?提前致谢!

【问题讨论】:

  • 你确定数据库中有bid id吗?

标签: python sql pymysql


【解决方案1】:

您的 '123abc' 参数没有修改您用于 sql 查询的字符串。 改为:

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

【讨论】:

  • 这对 SQL 注入非常开放。
【解决方案2】:

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

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

注意:在查询中使用占位符 (%s) 并将附加对象传递给 execute() 的好处通常可以处理所有不同的变量类型(int、str、dates、... ) 为你。

查看docs 可以将哪些对象传递给execute()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多