【问题标题】:TypeError: unsupported operand type(s) for %: 'long' and 'str'类型错误:不支持的操作数类型 %:'long' 和 'str'
【发布时间】:2014-03-17 07:45:49
【问题描述】:

使用此代码:

current_time=time.localtime()
time_now=time.strftime('%H:%M:%S',current_time)

cursor.execute("Select * from SUBSCRIPTION_DETAILS where Alert_time='%s'") % time_now

我得到错误:

unsupported operand type(s) for %:long and str

Alert_time 中的type 是 varchar

【问题讨论】:

  • 您好,欢迎您。有时需要一段时间才能有人有时间回答您的问题,可能是几个小时,甚至可能是几天。耐心点! 5 分钟后再次询问通常被认为不是很友好:-)

标签: python-2.7 mysql-python typeerror


【解决方案1】:

你放错了%

你现在做的是:

cursor.execute("[snip]") % time_now

所以你在cursor.execute的结果上应用time_now

您想要的是使用带有字符串的%,如下所示:

cursor.execute("[snip]" % time_now)

但不要这样做,你应该使用:

cursor.execute("Select * from SUBSCRIPTION_DETAILS where Alert_time=%s", (time_now,))

请注意,这里我们将time_now 作为第二个参数传递,而不是使用% 运算符。这将确保查询得到适当的清理,以防止 SQL 注入攻击。

需要(有点难看)尾随 , 以确保第二个参数是一个元组。

【讨论】:

  • TypeError: 在字符串格式化期间并非所有参数都转换了我在更改代码时收到此错误
  • time_now=time.strftime('%H:%M:%S',current_time) cursor.execute("Select * from SUBSCRIPTION_DETAILS where Alert_time=?",(time_now,)
猜你喜欢
  • 2017-05-27
  • 2016-09-05
  • 2021-06-18
  • 2014-06-15
  • 2019-04-08
  • 2018-07-07
  • 2014-06-16
  • 2016-01-26
  • 2018-08-28
相关资源
最近更新 更多