【问题标题】:insert query: syntax error at or near ' '插入查询: ' ' 处或附近的语法错误
【发布时间】:2019-07-04 07:20:40
【问题描述】:

您好,我有这个小代码段,它使用一些 api 数据并将其插入到我的一个表中。尝试插入字符域时会出现问题。与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 插入时,脚本工作得很好,我只是想不通到底出了什么问题。

【问题讨论】:

    标签: python postgresql


    【解决方案1】:

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

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

    【讨论】:

    • 上帝,我想念最愚蠢的事情,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2018-01-26
    • 2014-04-26
    • 1970-01-01
    • 2017-02-20
    • 2021-12-04
    • 1970-01-01
    • 2013-09-10
    • 2017-06-10
    相关资源
    最近更新 更多