首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python mysql插入时发生内存泄漏

Python mysql插入时发生内存泄漏
EN

Stack Overflow用户
提问于 2018-07-15 00:45:26
回答 1查看 656关注 0票数 2

我使用Python3在MySQL中插入了数以百万计的行,但我发现内存使用量一直在增长,最终达到了64‘m。我试着诊断这个问题,下面是问题的复制品:假设我有100个CSV文件。每个文件包含50000行,我想将它们插入到数据库中。下面是一个示例代码:

代码语言:javascript
复制
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列的表:

代码语言:javascript
复制
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,所以我的内存将会爆炸。

我做错什么了吗?(我是数据库新手)如何控制内存使用?任何建议都将不胜感激!

编辑:我也根据评论和答案尝试了以下代码,但仍然不起作用:

代码语言:javascript
复制
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')
EN

回答 1

Stack Overflow用户

发布于 2018-07-15 00:59:29

尝试批处理执行,这个插入循环可能是问题所在。

你可以在任何中执行

代码语言:javascript
复制
c.executemany("INSERT INTO table (Value) VALUES (%s)",
    [('a'),('b')])

或者同时包含您想要的所有值的大型insert语句。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51341440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档