插入查询:''或附近的语法错误

时间:2019-07-03 23:12:38

标签: python postgresql

您好,我有这个小代码段,它消耗一些api数据并将其插入到我的一个表中。尝试插入charfield时会出现问题。类似于resort_id变量,我只是试图将一个表中的值插入到另一个表中


data = []
'''this will assign key pairs to insert into table Reports'''
for var in myresult:
    resort_id = var['id']
    resort_name = var['resort_name']
    weather = (snowfall_from(var['location']))
    date = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d")
    data.append({"resort_id" : resort_id, "resort_name" : resort_name, "date" : date, "snowfall" : weather["snowfall"], "bottom_mintemp" : weather["bottom_mintemp"], "bottom_maxtemp" : weather["bottom_maxtemp"],
     "middle_mintemp" : weather["middle_mintemp"], "middle_maxtemp" : weather["middle_maxtemp"], "top_mintemp" : weather["top_mintemp"], "top_maxtemp" : weather["top_maxtemp"]})

print (data)
'''data inserted into table Reports'''
for row in data:
    query = (
        f"INSERT INTO site_face_reports (resort_id_id, resort_name, todays_date, snowfall, bottom_mintemp, bottom_maxtemp, mid_mintemp, mid_maxtemp, top_mintemp, top_maxtemp)\n"
        f"VALUES ({row['resort_id']}, {row['resort_name']} ,'{row['date']}', {row['snowfall']}, {row['bottom_mintemp']}, {row['bottom_maxtemp']}, {row['middle_mintemp']}, {row['middle_maxtemp']}, {row['top_mintemp']}, {row['top_maxtemp']})"
    )
    dict_cur.execute(query)
    print(query)


这是要插入的行

{'resort_id': 14, 'resort_name': 'Mt. Baker Ski Area', 'date': '2019-07-03', 'snowfall': '0.0', 'bottom_mintemp': '46', 'bottom_maxtemp': '56', 'middle_mintemp': '47', 'middle_maxtemp': '51', 'top_mintemp': '45', 'top_maxtemp': '47'}

这是我收到的错误

psycopg2.ProgrammingError: syntax error at or near "Ski"
LINE 2: VALUES (14, Mt. Baker Ski Area ,'2019-07-03', 0.0, 46, 56, 4...

当我省略resort_name插入时,脚本完全可以正常工作,只是无法解决问题。

1 个答案:

答案 0 :(得分:1)

resort_name是字符串类型,需要用VALUES字段的类似方式用查询的date部分中的引号引起来:

 f"VALUES ({row['resort_id']}, '{row['resort_name']}' ,'{row['date']}', etc etc