MySql获取了很多内存问题

2024-10-04 11:27:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将数据从Mysql移动到Postgres,我的代码如下-

import os, re, time, codecs, glob, sqlite3
from StringIO import StringIO
import psycopg2, MySQLdb, datetime, decimal
from datetime  import date
import gc

tables = (['table1' , 27],)
conn = psycopg2.connect("dbname='xxx' user='xxx' host='localhost' password='xxx' ")
curpost = conn.cursor()
db = MySQLdb.connect(host="127.0.0.1", user="root", passwd="root" , unix_socket='/var/mysql/mysql.sock', port=3306 )
cur = db.cursor() 
cur.execute('use xxx;')

for t in tables:
    print t
    curpost.execute( "truncate table " + t[0] )
    cur.execute("select * from "+ t[0] )
    a = ','.join( '%s' for i in range(t[1]) )
    qry = "insert into " + t[0]  + " values ( " + a +" )" 
    print qry
    i = 0
    while True:
        rows = cur.fetchmany(5000)
        if not rows: break
        string = ''
        for row in rows:
            string = string +  ('|'.join([str(x) for x in row])) + "\n"                
        curpost.copy_from(StringIO(string),  t[0], sep="|", null="None" )
        i += curpost.rowcount
        print i  , " loaded"
        curpost.connection.commit()        
        del string, row, rows
        gc.collect()        

curpost.close()
cur.close()

对于小表,代码运行良好。然而,当mysql执行时,较大的一个(360万个记录)(当前执行(“select*from”+t[0])运行时,计算机上的内存利用率将放大。这是即使我使用了fetchmany和记录应该只有5000个成批。我也试过500张唱片,而且都是一样的。对于大型表,fetchmany似乎没有按照文档中的方式工作。。在

Edit-我添加了垃圾回收和del语句。内存仍然在膨胀,直到所有的记录都没有被处理。在

有什么想法吗?在


Tags: infromimportforexecutestringmysqlxxx
1条回答
网友
1楼 · 发布于 2024-10-04 11:27:56

对不起,如果我错了,你说你不想改变查询

但万一你别无选择,你可以试试:

替换此碎片:

cur.execute("select * from "+ t[0] )
a = ','.join( '%s' for i in range(t[1]) )
qry = "insert into " + t[0]  + " values ( " + a +" )" 
print qry
i = 0
while True:
        rows = cur.fetchmany(5000)

对于这个:

^{pr2}$

相关问题 更多 >