TypeError: not all arguments converted during string formatting Error in tuple python

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (78)

我试图在DB中保存一堆元组

 cursor = cnx.cursor()
         query = """INSERT INTO `TableA`
                     (`clientid`,
                    `createddatetime`,
                    `siteid`,...)
                 VALUES(?,?,?,...)"""

    cursor.executemany(query, listTosave)

我的listTosave包含像元组列表;

[('AS0001','1170',1,'1','未知',442,1,datetime.datetime(2018,5,28,23,0),datetime.datetime(2018,3,15,11 ,15),datetime.datetime(2018,3,15,10,56),datetime.datetime(2018,5,28,23,18,26),datetime.datetime(2018,5,28,23,59, 22),Decimal('15177.3184'),Decimal('15185.7562'),Decimal('8.4378'),Decimal('1313.0547'),Decimal('1313.6179'),Decimal('0.5632'),Decimal('0.0000' ),十进制('0.0000'),十进制('0.0000'),十进制('0.0000'),十进制('0.0000'),十进制('0.0000'),十进制('24 .6518'),十进制('24 .6518') ,15101.7062,0.0,0.0,0.0,24.6563),(............)]

当我保存时得到:

 File "/tmp/pymodules/pymysql/cursors.py", line 194, in executemany
  File "/tmp/pymodules/pymysql/cursors.py", line 194, in <genexpr>
  File "/tmp/pymodules/pymysql/cursors.py", line 163, in execute
  File "/tmp/pymodules/pymysql/cursors.py", line 142, in mogrify
TypeError: not all arguments converted during string formatting

为什么我会得到这个错误?

提问于
用户回答回答于

它可能与存储在列表中的日期时间对象有关,而不是正确地转换为字符串表示。将这些包装起来str()可能是导致问题的原因。

请注意以下示例:

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2018, 5, 31, 8, 42, 48, 172575)
>>> str(datetime.datetime.now())
'2018-05-31 08:42:53.192586'

另一个选项可能能够通过使用json.dumps列表元素为json字符串格式来摆脱你的错误。但这取决于你想如何将数据存储在数据库中。请参阅以下内容:

>>> import json
>>> element = (
... 'AS0001', '1170', '1', '1', 'Unknown', '442', '1', '2018-05-28 23:00:00', '2018-03-15 11:15:00', '2018-03-15 10:56:00',
... '2018-05-28 23:18:26', '2018-05-28 23:59:22', '15177.3184', '15185.7562', '8.4378', '1313.0547', '1313.6179', '0.5632',
... '0.0000', '0.0000', '0.0000', '0.0000', '0.0000', '0.0000', '24.6518', '24.6518', '15101.7062', '0.0', '0.0', '0.0',
... '24.6563')
>>> json.dumps(element)
'["AS0001", "1170", "1", "1", "Unknown", "442", "1", "2018-05-28 23:00:00", "2018-03-15 11:15:00", "2018-03-15 10:56:00", "2018-05-28 23:18:26", "2018-05-28 23:59:22", "15177.3184", "15185.7562", "8.4378", "1313.0547", "1313.6179", "0.5632", "0.0000", "0.0000", "0.0000", "0.0000", "0.0000", "0.0000", "24.6518", "24.6518", "15101.7062", "0.0", "0.0", "0.0", "24.6563"]'

当检索这些数据时,你可以使用json.loads将其加载回python对象格式

扫码关注云+社区

领取腾讯云代金券