Python Bulk Insert提供TypeError:并非在字符串格式化期间转换所有参数

时间:2018-05-30 06:35:33

标签: python mysql pymysql

我有以下代码来插入多行;

cnx = pymysql.connect(host='xx', user='xx', password='xx', database='xx', autocommit=True)
cursor = cnx.cursor()
query = "INSERT INTO `tableA`('id,'name',...)values(?,? ......)"
cursor.executemany(query, listTosave)

我的listTosave包含像

这样的值
[['AS0001', '1170', 1, '1', 'Unknown', 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')],[......],...
....]]

当我尝试插入时,我得到以下错误;

    cursor.executemany(query, listTosave)
  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

我在这里做错了什么? 我想一次插入多行。

1 个答案:

答案 0 :(得分:1)

listTosave应该是元组列表而不是列表列表

[('AS0001', '1170', 1, '1', 'Unknown', 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')),(......),...]