如何使用 Python 将 JSONB 插入到 Postgresql 中?
How to insert JSONB into Postgresql with Python?
我是 python 和 postgresql
的新手
我一直在努力用 python 对每个 json 行进行硬编码,我认为这不是可扩展的方法。如果有人可以向我指出无需硬编码即可处理从 python 插入 json 的文献或文档。
我查看了 COPY。
有数据集+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)
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])
输出:
[1, [2, 3], {'a': [4, 5]}]
我是 python 和 postgresql
的新手我一直在努力用 python 对每个 json 行进行硬编码,我认为这不是可扩展的方法。如果有人可以向我指出无需硬编码即可处理从 python 插入 json 的文献或文档。
我查看了 COPY。
有数据集+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)
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])
输出:
[1, [2, 3], {'a': [4, 5]}]