【问题标题】:Mysql cursor throwing error while giving value dynmicalliyMysql游标在动态赋值时抛出错误
【发布时间】:2019-08-29 06:49:45
【问题描述】:

我正在使用 select 语句声明 mysql 游标并使用变量传递数据库名称但出现错误。我正在使用 python 2.7 和 mysql 5.6 版 使用 MySQLdb 包。

我已经尝试了通过堆栈溢出提供的所有方法。 cur.execute("select distinct U.user,U.password,U.host from user U,db D where U.user=D.user and D.db=%s and U.host= '%' order by user ;",[db])

cur.execute("select distinct U.user,U.password,U.host from user U,db D where U.user=D.user and D.db=%s and U.host= '%'按用户排序;",db)

cur.execute("select distinct U.user,U.password,U.host from user U,db D where U.user=D.user and D.db=%s and U.host= '%'按用户订购;",(db))

cur.execute("select distinct U.user,U.password,U.host from user U,db D where U.user=D.user and D.db=%s and U.host= '%'按用户排序;",db)

MySQLdb.connect(host='##############',user='#####,passwd='###',db='mysql')
    cur = conn.cursor()
    db="mysql"
    query = """select distinct U.user,U.password,U.host from user U,db D where U.user=D.user and D.db=%s and U.host= '%' order by user;"""
    cur.execute(query, (db))```

expecting values from tables but getting error.
ValueError: unsupported format character ''' (0x27) at index 104

【问题讨论】:

    标签: python-2.7 mysql-python


    【解决方案1】:

    这里:

    and U.host= '%' 
    

    's'不见了,你想要

    and U.host= '%s'
    

    另请注意,您的查询需要两个参数(您只传递一个):

    " D.db=%s and U.host= '%s'"
    

    如你所愿:

    cur.execute(query, (db, host))
    

    此外,FWIW,(db) 不会创建元组,您需要 (db,)(带逗号)。实际上它是创建一个元组的逗号,而不是括号(当然除了空元组......),在这里你只需要括号来强制将表达式评估为一个元组,因为你在函数的创建元组参数列表。

    【讨论】:

      【解决方案2】:
      Below one worked for me.
      
      db='mysql'
      query = "select distinct U.user,U.password,U.host from user U,db D where U.user=D.user and D.db='{}' and U.host= '%' order by user;".format(db)
      cur.execute(query)
      

      【讨论】:

      • 请不要建议以危害安全的方式滥用 db-api(bobby-tables.com 了解更多)
      • 审阅者注意:VLQ 队列不用于判断答案的技术优点。如果你认为这个答案是错误的,你应该投票和评论(不是投票删除)。
      • 20k+ users 有权投票删除得分为 -1 或更低的答案,例如投票删除会危及安全的答案。在 Super User、Ask Ubuntu 和 Unix & Linux Stack Exchange 等 SO 姐妹网站中,这是一个真正的问题。这是遵循@EJoshusS 的建议来评论(我做了)而不是投票删除(我没有投票删除)。
      猜你喜欢
      • 2021-11-13
      • 2011-06-10
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      相关资源
      最近更新 更多