我试图遍历一个sqlite数据库(我称之为database a),从其中的数据创建一些新变量,然后将这些新数据写入一个新的sqlite数据库(database b)。
数据库A是由表组成的,这些表由关于某个月的特定术语的tweet组成(每个tweet及其元数据是一行,包括该月的每一天)。每个表的大小约为0.5 GB。
所以,我遍历这些表,创建一个变量,然后将这个新数据写入/提交到数据库B。
问题是,在遍历了几个表之后,我使用的服务器上的工作内存(我有16GB的RAM)就完全用完了(使用
free -m
命令在bash中,我可以看到大约一半的ram被“buff/cache”使用。这不会生成任何可以在输出文件中看到的错误(通常显示python错误消息),但脚本将停止运行。
我认为这是sqlite创建临时文件的结果(
https://www.sqlite.org/tempfiles.html
,随着for循环的继续,它将继续增长。因此,我尝试逐日遍历表中的行,并在每天之后将新数据提交到数据库B,以便删除回滚日志(请参见上面的链接)(这些临时SQL文件之一)(从而释放内存)。然而,即使在做了这些更改之后,我也遇到了同样的问题(脚本停止)。
我不确定这里的代码有多大帮助,但这里有一个我正在做的基本概述:
import sqlite3
import pandas
#this defines the SQL query; [long list of columns] is just comma separated column names: id, date, time, etc.
sql_query = ("SELECT DISTINCT [long list of columns] "
"FROM term "
"WHERE date = 'day';")
### HERE I GET ALL TABLES IN DATABASE A ###
#go through all the tables in Database A
for t in tables:
term = t
### HERE I GET THE DAYS IN THE CURRENT TABLE ###
#go through each day in the current table in Database A
for day in days:
#open the databases
connection = sqlite3.connect("../SQL_database/Database_A.db3")
lite_cursor = connection.cursor()
connection_new = sqlite3.connect("../SQL_database/Database_B.db3")
lite_cursor_new = connection_new.cursor()
#change SQL query to match current day and term
sql_query = sql_query.replace('day', day)
#extract the data from the database and put it in the new database
for chunk in pandas.read_sql_query(sql_query, connection, chunksize = 10000):
### HERE I PROCESS THE DATA ###
#add the current data set to Database B
new_table = term
chunk.to_sql(new_table, connection_new, if_exists='append', index=True)
#redefine SQL query; [long list of columns] is just comma separated column names: id, date, time, etc.
sql_query = ("SELECT DISTINCT [long list of columns] "
"FROM term "
"WHERE date = 'day';")
#commit the changes
connection_new.commit()
#close the databases
connection.close()
connection_new.close()
当然,我想要的是脚本运行时不停顿/崩溃!有没有什么方法可以清除sqlite内存缓存,以便在for循环继续时不会耗尽ram?我以为commit()会释放一些内存,但显然它释放的内存不够。
提前谢谢你!