2017-07-17 80 views
0

因此,我在Python3.5上使用psycopg2將一些數據插入到postgresql數據庫中。我想要做的是有兩列是字符串,並且最後一列只是一個字典對象。我不需要搜索字典,只需將它從數據庫中取出並使用即可。添加dict對象到postgresql

所以例如:

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

這是可能的,如果是這樣我怎麼會去這樣做呢?

回答

3

如果您的PostgreSQL版本足夠新(9.4+)且psycopg版本大於2.5.4,則所有的鍵都是字符串,並且值可以表示爲JSON,最好將其存儲到JSONB列中。然後,如果需要,列也可以搜索。只要創建該表只是作爲

CREATE TABLE thetable (
    uuid TEXT, 
    dict JSONB 
); 

(...並根據需要自然地添加索引,主鍵等) 當發送詞典到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'})]) 

和選擇將是一樣簡單

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 

隨着JSONB時,PostgreSQL可以更有效地存儲的值而不僅僅是將字典傾倒爲文本。另外,可以做查詢的數據,例如只需要選擇一些來自JSONB列字段:

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

或者如果需要的話,你可以在查詢中使用它們:

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

那麼如果我需要返回整個字典對象,我可以這樣做返回行['字典']? – sbeyeler

+0

@sbeyeler可以使用任何可以使用'json.dumps'的數據結構。 –

1

您可以在存儲數據之前序列化使用JSON數據:檢索代碼時

import json 

data = json.dumps({'id':'122','name':'test','number':'444-444-4444'}) 

然後你反序列化:

cur.execute('SELECT dict from ....') 
res = cur.fetchone() 

dict = json.loads(res['dict']) 
print(dict['number'])