Python fetchall吃掉我所有的交换内存

时间:2015-03-12 16:05:28

标签: python sqlite cursor fetchall

我在一个表上执行一个查询,我得到一个有几亿行的列,这是因为我想在直方图中绘制它们。问题是,在完成cur.fetchall()之前程序退出时退出代码-9之前几乎占用了所有内存(7.8 gb)和所有交换内存(8gb)。

如何防止这种情况发生?我应该先对我的列进行排序,然后对其中的几个进行排序 - 或者是否有更好的方法来获取查询中的数据? cur.execute本身几乎没有时间。

#!/usr/bin/python

import sqlite3 as lite
import numpy as np
import sys
import os
import matplotlib.pyplot as plt


def getQuantity(databasepath):
    con = lite.connect(databasepath)
    binwidth = 1
    start = time.time()
    with con:
        cur = con.cursor()
        cur.execute('SELECT latitude FROM MessageType1')
        con.commit()
        latitudes = cur.fetchall() #Breakdown here
        latitudes = [x[0] for x in latitudes]
        plt.hist(latitudes, bins=range(int(min(latitudes)), int(max(latitudes)) + binwidth, binwidth))
        plt.title("Bucket size: " + str(binwidth))
        plt.ylabel("Number of message")
        plt.savefig('latlongstats'+'t'+str(time.strftime("%H:%M:%S")), format='png')

if __name__ == "__main__":

    getQuantity('database/database.db')

1 个答案:

答案 0 :(得分:0)

我发现如果我更换了以下内容:

    latitudes = cur.fetchall()
    print "fetched"
    latitudes = [x[0] for x in latitudes]

使用:

    while True:
        tmp = cur.fetchone()
        if tmp != None:
            latitudes.append(tmp[0])
        else:
            break

我得到了相同的结果,虽然它需要永远,但只是差点吃掉我的公羊(但不是我的交换)。