我使用Python3在MySQL中插入了数以百万计的行,但我发现内存使用量一直在增长,最终达到了64‘m。我试着诊断这个问题,下面是问题的复制品:假设我有100个CSV文件。每个文件包含50000行,我想将它们插入到数据库中。下面是一个示例代码:
import mysql.connector
insert_sql = ("INSERT INTO table (Value) VALUES (%s)")
for i in range(100):
cnx = mysql.connector.connect(user='root', password='password', host='127.0.0.1', database='database')
cursor = cnx.cursor()
# Insert 50000 rows here
for j in range(50000):
cursor.execute(insert_sql, (j,))
cnx.commit()
cursor.close()
cnx.close()
print('Finished processing one file')
print('All done')
数据库只包含一个包含2列的表:
CREATE TABLE `table` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Value` int(11) NOT NULL,
PRIMARY KEY (`Id`)
)
环境: Mac OS Sierra;Python3.6.x;MySQL 8.0.1;mysql-connector-python 8.0.11
我理解在提交之前内存应该增长,因为更改是缓冲的。但我认为在提交后它会减少。然而,它并不是。因为在我的实际应用程序中,我有数千个文件,每个文件都有100MB,所以我的内存将会爆炸。
我做错什么了吗?(我是数据库新手)如何控制内存使用?任何建议都将不胜感激!
编辑:我也根据评论和答案尝试了以下代码,但仍然不起作用:
import mysql.connector
insert_sql = ("INSERT INTO table (Value) VALUES (%s)")
for i in range(100):
cnx = mysql.connector.connect(user='root', password='password', host='127.0.0.1', database='database')
cursor = cnx.cursor()
params = [(j,) for j in range(50000)]
# If I don't excute the following insertion, the memory is stable.
cnx.executemany(insert_sql, params)
cnx.commit()
cursor.close()
del cursor
cnx.close()
del cnx
print('Finished processing one file')
print('All done')
发布于 2018-07-15 00:59:29
尝试批处理执行,这个插入循环可能是问题所在。
你可以在任何中执行
c.executemany("INSERT INTO table (Value) VALUES (%s)",
[('a'),('b')])
或者同时包含您想要的所有值的大型insert语句。
https://stackoverflow.com/questions/51341440
复制相似问题