所以我试图使用for循环将python字典中的数据输入到postgres数据库中。这是代码
for value in dic:
domain_desc = value["domain_desc"]
commodity_desc = value["commodity_desc"]
statisticcat_desc = value["statisticcat_desc"]
agg_level_desc = value["agg_level_desc"]
country_name = value["country_name"]
state_name = value["state_name"]
county_name = value["county_name"]
unit_desc = value["unit_desc"]
value1 = value["Value"]
year_val = value["year"]
cur.execute("INSERT INTO fact_data (domain_desc,commodity_desc,statisticcat_desc,agg_level_desc,country_name,state_name,county_name,unit_desc,value,year) VALUES (domain_desc,commodity_desc,statisticcat_desc,agg_level_desc,country_name,state_name,county_name,unit_desc,value1,year_val)")
cur.commit()
print("Success!")
我一直收到错误
追踪(最近一次通话): 文件“C:/Users/Backup/PycharmProjects/gro-app/harvest.py”,第123行, cur.execute(“INSERT INTO fact_data(domain_desc,commodity_desc,statisticcat_desc,agg_level_desc,country_name,state_name,county_name,unit_desc,value,year)VALUES(domain_desc,commodity_desc,statisticcat_desc,agg_level_desc,country_name,state_name,county_name,unit_desc,value1,year_val )“) psycopg2.ProgrammingError:列“domain_desc”不存在 第1行:... te_name,county_name,unit_desc,value,year)VALUES(domain_des ... ^ 提示:表“fact_data”中有一个名为“domain_desc”的列,但不能从查询的这一部分引用它。
我有正确的数据库和表格。导致此错误的原因是什么?我发现了一个类似的问题,但我不理解错误及其在不同的背景下 有人帮我理解这个
答案 0 :(得分:-2)
我认为你需要在值中添加变量,并使用+来连接字符串:
cur.execute("INSERT INTO fact_data (domain_desc,commodity_desc,statisticcat_desc,agg_level_desc,country_name,state_name,county_name,unit_desc,value,year) VALUES (" + ', '.join(map(str, (domain_desc,commodity_desc,statisticcat_desc,agg_level_desc,country_name,state_name,county_name,unit_desc,value1,year_val))) + ")")
考虑使用map从变量中创建字符串,连接以将它们连接到一个长字符串。
我甚至建议您单独进行,以使其更具可读性:
dict_value = ', '.join(map(str, (domain_desc,commodity_desc,statisticcat_desc,agg_level_desc,country_name,state_name,county_name,unit_desc,value1,year_val)))
cur.execute("INSERT INTO fact_data (domain_desc,commodity_desc,statisticcat_desc,agg_level_desc,country_name,state_name,county_name,unit_desc,value,year) VALUES (" + dict_value + ")"