我想将python字典作为json插入我的postgresql数据库(通过python和psycopg2).

我有:

thedictionary = {'price money': '$1', 'name': 'Google', 'color': '', 'imgurl': 'http://www.google.com/images/nav_logo225.png', 'charateristics': 'No Description', 'store': 'google'}

cur.execute("INSERT INTO product(store_id, url, price, charecteristics, color, dimensions) VALUES (%d, %s, %s, %d, %s, %s)", (1,  'http://www.google.com', '$20', thedictionary, 'red', '8.5x11'))

它给出了错误信息:

cur.执行("插入产品(store 标识、url、价格、特征、 colored颜色 、尺寸)值(%d、%s、%s、%d、%s、%s)",(1,'http://www.google.com','20',插图,'red','8.5x11'))

我不知道如何从这里开始.

推荐答案

cur.execute("INSERT INTO product(store_id, url, price, charecteristics, color, dimensions) VALUES (%s, %s, %s, %s, %s, %s)", (1,  'http://www.google.com', '$20', json.dumps(thedictionary), 'red', '8.5x11'))

那会解决你的问题.但是,您确实应该将键和值存储在各自的列中.要检索词典,请执行以下操作:

cur.execute('select charecteristics from product where store_id = 1')
dictionary = json.loads(cur.fetchone()[0])

Postgresql相关问答推荐

Docker化的PostgreSQL:FATAL:用户&postgres的密码身份验证失败

为什么不能超过 10 个并发连接到 Postgres RDS 数据库

gorm 不生成字符串列

postgres 中的模式前缀,被调用元素的范围

如何在 PostgreSQL 的回归测试中测试 TYPE 发送和接收函数

查找列中的数据是否满足sql中的数据类型条件

连接 Supbase Postgresql 数据库时,Stepzen Graphiql 资源管理器中的主机名解析错误

使用 Heroku CLI、Postgres 的 SQL 语法错误

使用间隔参数的 go postgres 准备好的语句不起作用

postgresql查询中的正则表达式不区分大小写

Rails:创建删除表级联迁移

运算符不存在:integer = integer[] 在使用 ANY 的查询中

Docker - Postgres 和 pgAdmin 4:Connection refused

为什么 sqlalchemy 的默认列值不起作用

从time without time zone和时区名称中获取time with time zone

Django:按月查询组

在 Postgresql 中按窗口函数结果过滤

如何从 PostgreSQL 中的 Json 数组中获取元素

使用 Postgres 在 Rust 的 Diesel 库中添加时间戳

IF处或附近的 Postgres 语法错误