我有一個按以下順序包含四列的 postgresql 表:created_at、id、author_id、text
我使用 twitters API 來獲取符合我的條件的推文(使用 Python)。Twitter API 只允許每個請求 500 條推文,這意味著如果我的搜索查詢回傳超過 500 條,我必須多次請求 - 就是這種情況。我想將 json 條目插入到我的 postgres 表中
# get column names from json object
columns=[list(x.keys()) for x in response['data']][0] # creates ['created_at','id','author_id','text']
# get the data from the response
data = json_response['data']
# write entries into postgres table
for item in data:
my_data = [item[column] for column in columns]
cur.execute("INSERT INTO tweets VALUES(%s, %s, %s, %s)", tuple(my_data))
現在,如果回傳的回應與我的 sql 表具有相同的順序,這可以正常作業。但是,json 回應可能具有不同的鍵順序。它現在可能是“id”、“author_id”、“text”、“created_at”。
然后我收到錯誤“型別 bigint 的無效輸入語法:...”
有什么方法可以在插入時保留相同的順序,即使 json 物件每次都有不同的順序?
uj5u.com熱心網友回復:
您可以使用命名變數,dict而不是tuple:
my_data = {'created_at': '', 'id': '', 'author_id': '...', 'text': '...'}
cur.execute(
"INSERT INTO tweets VALUES(%(created_at)s, %(id)s, %(author_id)s, %(text)s)",
my_data
)
如果所有鍵都存在于 中item,您可以簡單地傳遞item給執行,無需構建my_data。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/346951.html
標籤:Python PostgreSQL 字典 sql 插入
上一篇:可見性地圖:所有可見頁面
