我不明白为什么这不起作用。我试图将字符串列表作为用作数据库查询的字符串内循环的一部分传递。这是我收到的错误:
\porfiler03.ar.local\gtdshare\vortex\monthly_variability\scripts\wind_index_chinook_region_3plots_working_monthly.py:71 in get_db_data
crs_obj.execute(query)
UndefinedColumn: column "east" does not exist
LINE 5: ...s_name = 'UNITED STATES' AND maint_region_name = EAST AND ...
这是代码:
regions = ['EAST','CENTRAL']
for x in regions:
randall_query = f"""select plant_mos_adj_wind.plant_name, plant_mos_adj_wind.business_name,plant_mos_adj_wind.business_code,plant_mos_adj_wind.wind_speed_ms,
plant_mos_adj_wind.maint_region_name, plant_mos_adj_wind.wind_direction_deg, plant_mos_adj_wind.mos_time, plant_mos_adj_wind.total_current_capacity,
plant_mos_adj_wind.dataset
from vortex.plant_mos_adj_wind
where business_name = 'UNITED STATES' AND maint_region_name = {x} AND dataset = 'ERA5'"""
try:
connection = psycopg2.connect(user="cms_app",
password="xxxxx",
host="frupaapg02.ar.local",
port="xxxx",
database="xxxx")
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
postgreSQL_select_Query = f"""select plant_name, business_name, maint_region_name, total_current_capacity, mos_time, wind_speed_ms, wind_direction_deg, dataset
from vortex.plant_mos_adj_wind
where business_name = 'UNITED STATES' AND maint_region_name = {x} AND dataset = 'ERA5'"""
cursor.execute(postgreSQL_select_Query)
chinookmos_records = cursor.fetchall()
finally:
#closing database connection.
if(connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
#iterate the columns
print("Column headers for cdata are:")
for col in cdata.columns:
print(col)
这应该使用 f 字符串函数并替换区域中的 x 来工作,但是您可以看到它由于 EAST 参数而失败,并且显然应该是“EAST”传递,因为我的想法是字符串。
我推荐2个解决方案:
randall_query = f"""select plant_mos_adj_wind.plant_name, plant_mos_adj_wind.business_name,plant_mos_adj_wind.business_code,plant_mos_adj_wind.wind_speed_ms, plant_mos_adj_wind.maint_region_name, plant_mos_adj_wind.wind_direction_deg, plant_mos_adj_wind.mos_time, plant_mos_adj_wind.total_current_capacity, plant_mos_adj_wind.dataset from vortex.plant_mos_adj_wind where business_name = 'UNITED STATES' AND maint_region_name = {x} AND dataset = 'ERA5'"""
f string 只是将变量的值放入字符串中,因此您需要在 {x} 中添加单引号('')。
转换这个 AND maint_region_name = {x}
对此: AND maint_region_name = '{x}'