简体   繁体   English

如何使用 Python 将 JSONB 插入 Postgresql?

[英]How to insert JSONB into Postgresql with Python?

I am new to python and postgresql我是 python 和 postgresql 的新手

I've been battling just hardcoding each json line with python and I don't think this the scalable method.我一直在努力用 python 对每个 json 行进行硬编码,我认为这不是可扩展的方法。 If someone can point me to the literature or documentation that can handle json insertion from python without hardcoding.如果有人可以指出我可以在没有硬编码的情况下处理来自 python 的 json 插入的文献或文档。

I've looked into COPY.我已经研究过 COPY。

import json

data = [1, [2,3], {'a': [4,5]}]
my_json = json.dumps(data)
insert_query = "insert into t (j) values (%s) returning j"
cursor.execute(insert_query, (my_json,))
print (cursor.fetchone()[0])

Output:输出:

[1, [2, 3], {'a': [4, 5]}]

With dataset + psycopg2使用数据集 + psycopg2

import dataset

def construct_pg_url(postgres_user='postgres', postgres_password='', postgres_host='localhost', postgres_port='5432', postgres_database='postgres'):
    PG_URL = "postgresql://" + postgres_user + ":" + postgres_password + '@' + postgres_host + ':' + postgres_port + '/' + postgres_database
    return PG_URL

pgconn = dataset.Database(
             url=construct_pg_url(),
             schema='my_schema'
)
table = pgconn['my_table']
rows = [dict(foo='bar', baz='foo')] * 10000
table.insert_many(rows)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM