我有一个json数据要插入到表中, 这是JSON数据,
data1 = [
{
'Design Project': 'Not Available',
'Design Target*': 'Not Available',
'Median Property*': '50',
'Metric': 'ENERGY STAR score (1-100)'
},
{
'Design Project': 'Not Available',
'Design Target*': '35.4',
'Median Property*': '141.4',
'Metric': 'Source EUI (kBtu/ft\\u00b2)'
},
{
'Design Project': 'Not Available',
'Design Target*': '15.8',
'Median Property*': '63.1',
'Metric': 'Site EUI (kBtu/ft\\u00b2)'
},
{
'Design Project': 'Not Available',
'Design Target*': '3,536.0',
'Median Property*': '14,144.1',
'Metric': 'Source Energy Use (kBtu)'
},
{
'Design Project': 'Not Available',
'Design Target*': '1,578.7',
'Median Property*': '6,314.9',
'Metric': 'Site Energy Use (kBtu)'
},
{
'Design Project': 'Not Available',
'Design Target*': '34.61',
'Median Property*': '138.44',
'Metric': 'Energy Cost ($)'
},
{
'Design Project': '0.0',
'Design Target*': '0.2',
'Median Property*': '0.6',
'Metric': 'Total GHG Emissions (Metric Tons CO2e)'
}
]
我有表结构,
project_id | metric | design_target | median_property | design_project
-----------+--------+---------------+-----------------+---------------
我有一个project_id变量,如
PROJECT_ID = 400
我的查询将数据插入Postgres的表中,我试过,
cur.executemany(
"""INSERT INTO Metric_Comparison(Project_id, Metric, Design_Target, Median_Property, Design_Project)
VALUES (%(PROJECT_ID)s, %(Metric)s, %(Design Target*)s, %(Median Property*)s, %(Design Project)s)""",
data1
)
如何在插入表格时附加项目ID?
答案 0 :(得分:1)
如何通过字符串格式化查询来输入项目ID?
PROJECT_ID = 400
cur.executemany("""
INSERT INTO Metric_Comparison
(Project_id,Metric,Design_Target,Median_Property,Design_Project)
VALUES ({}, %(Metric)s, %(Design Target*)s, %(Median Property*)s, %(Design Project)s)
""".format(PROJECT_ID), data1)
答案 1 :(得分:0)
您可以创建新的dict并将项目ID添加到其中:
enriched_data = {}
project_id = 100
for key, value in data1:
enriched_data[key] = dict(value)
enriched_data[key]["PROJECT_ID"] = project_id
sql_query = "..."
cur.executemany(sql_query, enriched_data)