将dict对象添加到postgresql

sbe*_*ler 6 python postgresql dictionary psycopg2

所以我在Python3.5上使用psycopg2将一些数据插入到postgresql数据库中.我想要做的是有两列是字符串,最后一列只是一个dict对象.我不需要搜索dict,只需能将其从数据库中取出并使用它.

例如:

uuid = "testName"
otherString = ""
dict = {'id':'122','name':'test','number':'444-444-4444'}

# add code here to store two strings and dict to postgresql

cur.execute('''SELECT dict FROM table where uuid = %s''', 'testName')
newDict = cur.fetchone()
print(newDict['number'])
Run Code Online (Sandbox Code Playgroud)

这是可能的,如果是这样,我该怎么做呢?

Ant*_*ala 13

如果您的PostgreSQL版本足够新(9.4+)且psycopg版本> = 2.5.4,则所有键都是字符串,值可以表示为JSON,最好将其存储到JSONB列中.然后,如果需要,该列也将是可搜索的.只需创建表格即可

CREATE TABLE thetable (
    uuid TEXT,
    dict JSONB
);
Run Code Online (Sandbox Code Playgroud)

(...并根据需要自然地添加索引,主键等...)当将字典发送到PostgreSQL时,您只需要使用Json适配器包装它 ; 当从PostgreSQL接收时,JSONB值将自动转换为字典,因此插入将变为

from psycopg2.extras import Json, DictCursor

cur = conn.cursor(cursor_factory=DictCursor)

cur.execute('INSERT into thetable (uuid, dict) values (%s, %s)',
    ['testName', Json({'id':'122','name':'test','number':'444-444-4444'})])
Run Code Online (Sandbox Code Playgroud)

选择就像一样简单

cur.execute('SELECT dict FROM thetable where uuid = %s', ['testName'])
row = cur.fetchone()
print(row['dict']) # its now a dictionary object with all the keys restored
print(row['dict']['number']) # the value of the number key
Run Code Online (Sandbox Code Playgroud)

使用JSONB,PostgreSQL可以更有效地存储值,而不仅仅是将字典转储为文本.此外,可以使用数据进行查询,例如,只需从JSONB列中选择一些字段:

>>> cur.execute("SELECT dict->>'id', dict->>'number' FROM thetable")
>>> cur.fetchone()
['122', '444-444-4444']
Run Code Online (Sandbox Code Playgroud)

或者你可以在需要时在查询中使用它们:

>>> cur.execute("SELECT uuid FROM thetable WHERE dict->>'number' = %s',
    ['444-444-4444'])
>>> cur.fetchall()
[['testName', {'id': '122', 'name': 'test', 'number': '444-444-4444'}]]
Run Code Online (Sandbox Code Playgroud)