-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostgres.py
More file actions
78 lines (69 loc) · 2.47 KB
/
postgres.py
File metadata and controls
78 lines (69 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# !/usr/bin/python3
# -*- coding: utf-8 -*-
import json
import psycopg2
from psycopg2 import connect, Error
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
import sys
try:
connection = psycopg2.connect(user="postgres",
# пароль, который указали при установке PostgreSQL
password="",
host="127.0.0.1",
port="5432")
connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cursor = connection.cursor()
create_table='''CREATE TABLE matches_info (
CPM integer,
KDA integer,
assists integer,
avatar varchar(400),
deaths integer,
duration varchar(40),
gold_per_min integer,
hero varchar(40),
hero_damage integer,
hero_healing integer,
kills integer,
last_hits integer,
match_result varchar(40),
nickname varchar(40),
profileurl varchar(200),
side varchar(40),
start_time varchar(200),
total_value integer,
tower_damage integer,
xp_per_min integer
);'''
# cursor.execute(create_table)
table_name = "matches_info"
cursor.execute(f"SELECT * FROM {table_name}")
record = cursor.fetchall()
for i in record:
print(i)
with open('result.json') as json_data:
record_list = json.load(json_data)
sql_string = 'INSERT INTO {} '.format(table_name)
if type(record_list) == list:
first_record = record_list[0]
columns = list(first_record.keys())
else:
sys.exit()
sql_string += "(" + ', '.join(columns) + ")\nVALUES "
for i, record_dict in enumerate(record_list):
values = []
for col_names, val in record_dict.items():
if type(val) == str:
val = val.replace("'", "''")
val = "'" + val + "'"
values += [str(val)]
sql_string += "(" + ', '.join(values) + "),\n"
sql_string = sql_string[:-2] + ";"
# cursor.execute(sql_string)
except (Exception, Error) as error:
print("Ошибка при работе с PostgreSQL", error)
finally:
if connection:
cursor.close()
connection.close()
print("Соединение с PostgreSQL закрыто")