【问题标题】:Select Array from MySQL in Python without For Loop在没有 For 循环的 Python 中从 MySQL 中选择数组
【发布时间】:2014-06-03 19:09:18
【问题描述】:

我试图在不使用 for 循环的情况下从我的 MySQL 中选择一组值。 for 循环需要很长时间,我想一次获取所有值。我不知道我的论点有什么问题,而且我很难解释我收到的错误消息是什么意思。

zipcode = ["37204", "60964", "60068"]
connection = MySQLdb.connect(host="localhost", user="root", passwd="password", db="database", cursorclass=MySQLdb.cursors.SSCursor)
cursor = connection.cursor()  
query = "SELECT fips FROM us WHERE zip = %s"
cursor.executemany(query,zipcode)
results = cursor.fetchall()

错误如下所示:

query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting

感谢任何帮助。

【问题讨论】:

  • 在邮政编码列表的声明中,您的逗号在第一个元素内。这是问题或代码中的错字吗?

标签: python mysql arrays


【解决方案1】:

Python 不是我的强项,我之前也没有使用过 executemany,但我认为它不应该用于执行应该返回某些内容的代码。您可能希望在查询中使用 IN。

query = "SELECT fips FROM us WHERE zip IN ('%s')" % "','".join(zipcode)
cursor.execute(query)
results = cursor.fetchall()

【讨论】:

  • 我不认为这是安全的,但如果你在其他地方控制你的输入,这应该可以工作
猜你喜欢
  • 2015-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-16
  • 2017-06-17
  • 2022-01-09
  • 2012-11-28
相关资源
最近更新 更多