在python中使用MySQLdb向数据库插入新元素时发生内存泄漏

2024-06-26 13:21:36 发布

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

我有一个包含图像列表的文件夹,我从中创建每个图像的哈希,并使用python中的MySQLdb将其逐个插入到sql数据库中。那个文件夹里有大约1400张图片,我需要把它们的哈希值存储在数据库中。但是,每次插入时,它都会消耗掉我的部分空闲RAM,最终得到的是0个空闲RAM空间,并且进程会被终止。我不明白为什么会发生这种情况,因为一次简单的插入不应该导致将整个数据库放入RAM中。因此,在执行插入操作时消耗的RAM量不应取决于数据库的大小。然而,我的公羊已经被时间填满了,尽管我正在这样做self.db.关闭()每次插入后。为什么会发生这种情况,我该怎么解决呢?在

代码如下:

def create_hash(userpath, hashfunc=imagehash.phash):
    print "here"
    image_filenames = [os.path.join(userpath, path)
                    for path in os.listdir(userpath) if is_image(path)]
    for img in sorted(image_filenames):
        try:
            hash_img = hashfunc(Image.open(img))
            img_url =  img.split("/")[-1]
            print hash_img
            c = Connection()
            c.insert(img_url, hash_img)
            c.close_connection()
        except Exception,e:
            print str(e)

下面是Connection类的insert函数:

^{pr2}$

请注意,我在上面的代码中使用了this imagehash python library


Tags: path代码图像image文件夹数据库img情况
1条回答
网友
1楼 · 发布于 2024-06-26 13:21:36

尝试在一个查询中插入多行。在

INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.

看,记忆还在流失。在

class Connection():
    def __init__(self):
        self.db = MySQLdb.connect("localhost","root","password","some_schema")
        self.cursor = self.db.cursor()

    def insert(self, values):
        query = "insert into image_hash (image_url, hash) values {0}".format(values)
        try:
            self.cursor.execute(query)
            self.db.commit()
        except Exception,e:
            self.db.rollback()
            print str(e)

    def close_connection(self):
        self.db.close()


def create_hash(userpath, hashfunc=imagehash.phash):
    _join = os.path.join
    image_filenames = [_join(userpath, path)
                       for path in os.listdir(userpath) if is_image(path)]
    hash_list = []
    for img in sorted(image_filenames):
        try:
            hash_img = hashfunc(Image.open(img))
            img_url =  img.split("/")[-1]
            hash_list.append("('{0}', '{1}')".format(img_url, hash_img))
        except Exception,e:
            print str(e)


    c = Connection()
    c.insert(', '.join(hash_list))
    c.close_connection()

相关问题 更多 >