psycopg2将python字典作为json插入 [英] psycopg2 insert python dictionary as json

查看:123
本文介绍了psycopg2将python字典作为json插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to insert a python dictionary as a json into my postgresql database (via python and 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.execute("INSERT INTO product(store_id,url,价格,特性,颜色,尺寸)VALUES(%d,%s,%s,%d,%s,%s)",(1,' http://www.google.com ','$ 20',thedictionary,'red','8.5x11' )) psycopg2.ProgrammingError:无法适应类型"dict"

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')) psycopg2.ProgrammingError: can't adapt type 'dict'

我不确定如何从这里继续. 我在互联网上找不到有关如何执行这种确切操作的任何信息,而我对psycopg2还是陌生的.

I am not sure how to proceed from here. I cannot find anything on the internet about how to do this exact kind of thing and I am very new to psycopg2.

推荐答案

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'))

那将解决您的问题.但是,您实际上应该将键和值存储在它们自己的单独列中.要检索字典,请执行以下操作:

That will solve your problem. However, you really should be storing keys and values in their own separate columns. To retrieve the dictionary, do:

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

这篇关于psycopg2将python字典作为json插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆