python - 使用 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: 数组值必须开始带有“{”或维度信息。
那么可能是什么问题,有没有办法让插入字典条目的过程更容易(意味着将列名与字典键匹配并相应地自动添加值)
解决方案
推荐阅读
- javascript - 将状态传递给另一个组件的正确方法
- python - 在python中的进程之间共享线程池
- c# - 在组级别而不是应用程序级别处理并发
- python - POST 请求适用于 POSTMAN,但不适用于 Python 和 cURL
- javascript - 替换 javascript nashorn:mozilla_compat.js 在 ant 脚本中使用
- php - 如何使用 Supervisor 在 AWS Lightsail 实例上运行 Websocket 服务器
- sql - 带有输入参数的查询不会编译为视图
- c# - 如何从数据库中读取位值并将该值设置为布尔会话变量(如果不为空)
- chat - 关于 Angular 8 sendbird 聊天的建议
- web-scraping - Scrapy init 返回一个 None