问题描述
我发现运行此 python 代码时出现内存问题,试图使用下面使用的 WHERE 参数提取数据,以尽可能减少数据提取。我开始使用“fetchall()”,但没有产生任何结果。现在,使用 fetchmany(batch_size) 并设置 batch_size = 8500000,程序将完成而不会因内存错误而崩溃。问题是我需要从数据库中读取更多记录。有没有办法逐块遍历,也许使用 fetchmany() 中的以下代码来执行等效于使用 fetchall() 的操作,以避免内存错误崩溃问题?错误指向下面代码中带有“内存错误”的最后一行。或者,在下面的代码中使用 fetchmany() 的替代方法?谢谢你的帮助,我真的很感激。
def get_db_data(crs_obj,query,asstring=False,testing=False):
"""Takes a given cursor object to a database,and executes a
given query. Returns the data as a dataframe.
"""
# crs_obj = conn_object.cursor()
if testing:
print(query)
crs_obj.execute(query)
names = list()
for item in crs_obj.description:
names.append(item[0])
query_output = crs_obj.fetchmany(size=8500000)
df_output = pd.DataFrame(query_output,columns=names)
if asstring:
df_output = df_output.astype('str')
return df_output
randall_query = """select plant_mos_adj_wind.plant_name,plant_mos_adj_wind.business_name,lant_mos_adj_wind.maint_region_name,plant_mos_adj_wind.wind_speed_ms,plant_mos_adj_wind.mos_time,plant_mos_adj_wind.power_kwh,plant_mos_adj_wind.dataset
from vortex.plant_mos_adj_wind
where business_name = 'SPAIN' AND maint_region_name = 'ESTE' AND dataset = 'ERA5'"""
batch_size = 8500000
try:
connection = psycopg2.connect(user="cms_app",password="cms_app",host="frudaapg02.ar.local",port="5444",database="cms")
print("Selecting rows from vortex plant_mos_adj_wind table using cursor.fetchmany")
cursor = connection.cursor()
cdata = get_db_data(cursor,randall_query,False,True).round(1) #panda df
ostgresql_select_Query = """select plant_name,business_name,maint_region_name,mos_time,wind_speed_ms,power_kwh,dataset
from vortex.plant_mos_adj_wind
where business_name = 'SPAIN' AND maint_region_name = 'ESTE' AND dataset = 'ERA5'"""
cursor.execute(postgresql_select_Query)
chinookmos_records = cursor.fetchmany(batch_size)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)