Как вставить JSONB в Postgresql с помощью Python?

#python #json #python-3.x #database #postgresql

Вопрос:

Я новичок в python и postgresql

Я боролся просто с жестким кодированием каждой строки json с помощью python, и я не думаю, что это масштабируемый метод. Если кто-нибудь может указать мне литературу или документацию, которая может обрабатывать вставку json из python без жесткого кодирования.

Я просмотрел КОПИЮ.

Ответ №1:

 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]}]
 

Комментарии:

1. Работает как заклинание! И не забывайте conn.autocommit = True или conn.commit не смотрите фактические результаты в базе данных.

Ответ №2:

С набором данных 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)