Как импортировать значения API в PostgreSQL?
Вытащил данные из Google Sheets API
Парсинг прошел успешно, прилагаю скрин
Но не могу вытащить данные в PostgreSQL
выбрал самый простой способ с помощью команд sql
connection = psycopg2.connect(
host=host,
user=user,
password=password,
database=db_name
)
connection.autocommit = True
# for row in rows:
# st1 = row[0], st2 = row[1], st3 = row[2], st4 = row[3]
# with connection.cursor() as cursor:
# cursor.execute(
# """CREATE TABLE test_c (
# № integer,
# заказ_№ integer,
# стоимость_$ integer,
# стоимость_РУБ integer,
# срок_поставки date);"""
# )
col1 = [row[0] for row in rows]
col2 = [row[1] for row in rows]
col3 = [row[2] for row in rows]
col4 = [row[2]*67 for row in rows] #курс $ через API вытащю, но пока так
col5 = [row[3] for row in rows]
print(col1)
"""INSERT data into a table"""
with connection.cursor() as cursor:
cursor.execute(
"""INSERT INTO test_c
(№, заказ_№, стоимость_$, стоимость_РУБ, срок_поставки)
VALUES (col1, col2, col3, col4, col5);"""
)
"""UPDATE data into a table"""
with connection.cursor() as cursor:
cursor.execute(
"""UPDATE test_c
SET № = [i for i in col1];"""
)
Но что-то явно делаю не так.
Хелпаните, плиз!
Ответы (1 шт):
Автор решения: Namerek
→ Ссылка
from psycopg2 import connect
from psycopg2.extras import execute_values
data = [['38', '1287751', '1891', '17.05.2022'],
['39', '1498932', '1162', '21.05.2022'],
['40', '1897398', '414', '01.06.2022'],
['41', '1810448', '1668', '11.05.2022'],
['42', '1168728', '658', '03.05.2022'],
['43', '1560222', '1587', '11.05.2022'],
['44', '1592686', '514', '23.05.2022'],
['45', '1786437', '618', '28.05.2022'],
['46', '1485012', '1124', '09.05.2022'],
['47', '1741017', '514', '16.05.2022'],
['48', '1497493', '1198', '30.05.2022'],
['49', '1877503', '1204', '29.05.2022'],
['50', '1426726', '1997', '20.05.2022']]
c = connect(
# your connection params
)
cr = c.cursor()
cr.execute(
"""
create table if not exists rate(
transaction_id int primary key ,
order_id int,
amount_usd numeric,
-- Сделано для примера,
-- при наличии курса заменить
amount_rub numeric generated always as ( amount_usd * 60 ) stored ,
term date
);
"""
)
execute_values(
cr,
"""
insert into rate (transaction_id, order_id, amount_usd, term)
VALUES %s
on conflict (transaction_id) do update
set order_id = excluded.order_id,
amount_usd = excluded.amount_usd,
term = excluded.term;
""",
data,
template="(%s, %s, %s, to_date(%s::text, 'DD.MM.YYYY'))",
page_size=100
)
c.commit()
cr.close()
c.close()
