首页 > 解决方案 > 使用 psycopg2 在 PSQL 中插入 python dict

问题描述

我想将以下 python 字典插入到具有与字典键相同的列名的 postgres 数据库表中,并且我尝试了以下代码

import psycopg2
import sys, os
import numpy as np
import pandas as pd
import pandas.io.sql as psql

# Set up a connection to the postgres server.
try:
    conn = psycopg2.connect("dbname='asd' user='asd' host='asd' password='asd'")
except:
    print ("I am unable to connect to the database")


cur = conn.cursor()
cur.execute("""set search_path to asd;""")


entry = {
    'pat_id': '100356',
    'event_id': '56',
     'subevent_id': '12324',
       'amount': '6543',
        'unit': 'm'}


cur.execute(""" INSERT INTO drugsdoc(pat_id,event_id,subevent_id,amount,unit) VALUES(%(pat_id)s,%(event_id)s,%(subevent_id)s,%(amount)s,%(unit)s)""",entry)

执行代码时出现以下错误

DataError:格式错误的数组文字:“m”第 1 行:...ent_id,amount,unit) VALUES('100356','56','12324','6543','m') ^ DETAIL: 数组值必须开始带有“{”或维度信息。

那么可能是什么问题,有没有办法让插入字典条目的过程更容易(意味着将列名与字典键匹配并相应地自动添加值)

标签: pythonsqlpostgresqlpsycopg2

解决方案


推荐阅读