-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjson_to_db.py
More file actions
34 lines (24 loc) · 1.06 KB
/
json_to_db.py
File metadata and controls
34 lines (24 loc) · 1.06 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
import sqlite3
import json
def import_from_json(db_path, json_path):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
with open(json_path, 'r', encoding='utf-8') as json_file:
database_data = json.load(json_file)
for table, rows in database_data.items():
if not rows:
continue
# Здесь предполагается, что таблица уже существует
try:
columns = list(rows[0].keys())
placeholders = ', '.join(['?'] * len(columns))
query = f"INSERT INTO {table} ({', '.join(columns)}) VALUES ({placeholders})"
for row in rows:
values = [row[column] if type(row[column]) is not list else '[' + ','.join(f'"{e}"' for e in row[column]) + ']' for column in columns]
cursor.execute(query, values)
except sqlite3.IntegrityError:
print(rows, 'is exists already')
conn.commit()
conn.close()
if __name__ == '__main__':
import_from_json('instance/app.db', 'fixtures/database_dump.json')