【问题标题】:Python MySQLdb type error while using execute with %s使用 %s 执行时 Python MySQLdb 类型错误
【发布时间】:2023-03-04 16:58:01
【问题描述】:

我从 python 中的一个简单的 mysql 查询开始,返回表的所有列。 由于某种原因,此命令有效:

cursor.execute("SHOW columns from students")

虽然以下所有内容都返回类型错误:

cursor.execute("SHOW columns from %s", 'students')

cursor.execute("SHOW columns from %s", ('students',))

cursor.execute("SHOW columns from %s", ['students'])

cursor.execute("""SHOW columns from %s""", 'students')

错误是:

Traceback (most recent call last):
File "<pyshell#60>", line 1, in <module>
    cursor.execute("SHOW columns from %s", 'students')
File "C:\Anaconda\lib\site-packages\MySQLdb\cursors.py", line 187, in   execute
query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting

请指教

【问题讨论】:

  • 第二种形式应该可以工作。您能否具体确认第二种形式的错误消息是什么?该示例仅显示第一个表单的错误。
  • 你试过cursor.execute("SHOW columns from (%s)", ['students'])吗?
  • 第二个错误:回溯(最近一次调用最后一次):文件“”,第 1 行,在 cursor.execute("SHOW columns from %s" , ('students',)) 文件“C:\Anaconda\lib\site-packages\MySQLdb\cursors.py”,第 205 行,在执行 self.errorhandler(self, exc, value) 文件“C:\Anaconda\ lib\site-packages\MySQLdb\connections.py”,第 36 行,在 defaulterrorhandler raise errorclass, errorvalue ProgrammingError: (1064, “您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本对应的手册以获取正确的在第 1 行的 ''students'' 附近使用的语法)

标签: python cursor mysql-python execute


【解决方案1】:

尝试使用格式化字符串的推荐方式:

cursor.execute("SHOW columns from {}".format('students'))

【讨论】:

  • 可能是因为在我的情况下只有参数,而在你的情况下有 2 个,第二个被视为传递给 cursor.execute() 的第二个参数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-23
  • 1970-01-01
  • 2010-11-01
  • 1970-01-01
  • 2013-12-26
  • 2010-09-16
  • 2015-12-27
相关资源
最近更新 更多