Python + MySQLdb 批量执行

7 投票
2 回答
14629 浏览
提问于 2025-04-15 12:09

我正在使用Python和它的MySQLdb模块,把一些测量数据导入到Mysql数据库中。我们拥有的数据量非常大(目前大约有250MB的csv文件,未来还会有更多)。

现在我用cursor.execute(...)来导入一些元数据。这没什么问题,因为这些数据的条目不多。

问题是,当我尝试使用cursor.executemany()来导入大量的实际测量数据时,MySQLdb会报错。

TypeError: not all arguments converted during string formatting

我现在的代码是

def __insert_values(self, values):
    cursor = self.connection.cursor()
    cursor.executemany("""
        insert into values (ensg, value, sampleid)
        values (%s, %s, %s)""", values)
    cursor.close()

其中values是一个包含三条字符串的元组列表。有没有人知道可能出什么问题了?

编辑:

这些值是通过

yield (prefix + row['id'], row['value'], sample_id)

生成的,然后每次读取一千条到一个列表中,row是来自csv.DictReader的一个迭代器。

2 个回答

3

你收到的消息表示在 executemany() 方法里面,有一个转换失败了。检查一下你的 values 列表,看看里面有没有长度超过3的元组。

为了快速验证一下:

max(map(len, values))

如果结果大于3,可以用过滤器找到出问题的元组:

[t for t in values if len(t) != 3]

或者,如果你需要知道索引的话:

[(i,t) for i,t in enumerate(values) if len(t) != 3]
8

回头看,这真是一个很傻但又不容易发现的错误。因为“values”在SQL中是一个关键字,所以表名“values”需要加上引号。

def __insert_values(self, values):
    cursor = self.connection.cursor()
    cursor.executemany("""
        insert into `values` (ensg, value, sampleid)
        values (%s, %s, %s)""", values)
    cursor.close()

撰写回答