mysql内存插入泄漏

guz6ccqo  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(458)

我正在使用python3在mysql中插入数百万行,但我发现内存使用量一直在增长,最终达到64gb。我试图诊断这个问题,这里是问题的再现:假设我有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')

数据库仅包含1个表和2列:

CREATE TABLE `table` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Value` int(11) NOT NULL,
  PRIMARY KEY (`Id`)
)

环境:mac os sierra;python 3.6.x版;mysql 8.0.1版本;mysql连接器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')
h22fl7wq

h22fl7wq1#

尝试批处理执行,这个插入循环可能就是问题所在。
您可以执行以下操作:

c.executemany("INSERT INTO table (Value) VALUES (%s)",
    [('a'),('b')])

或同时包含所有所需值的大insert语句。

相关问题