Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sqlite3
- from typing import Dict, List
- import json
- table1 = [
- "name1",
- "name2",
- "name3",
- ]
- table2 = [
- "name4",
- "name5",
- "name6",
- ]
- def extract_table(table : List[str], data) -> List[Dict]:
- data_rows = []
- for item in data:
- try:
- item_dict = json.loads(item)
- except json.JSONDecodeError:
- item_dict = {}
- row = {column: item_dict.get(column, None) for column in table}
- data_rows.append(row)
- return data_rows
- def get_all_data(json_file):
- with open(json_file, 'r', encoding='utf8') as handle:
- data = json.load(handle)
- data_table1 = extract_table(table1, data)
- data_table2 = extract_table(table2, data)
- def create_database():
- connection = sqlite3.connect("name.db")
- cursor = connection.cursor()
- cursor.execute(
- """CREATE TABLE IF NOT EXISTS t_table1 (
- name1 TEXT,
- name2 TEXT,
- name3 TEXT)"""
- )
- cursor.execute(
- """ CREATE TABLE IF NOT EXISTS t_table2 (
- name4 TEXT,
- name5 TEXT,
- name6 TEXT)"""
- )
- connection.commit()
- def load_data(table_name, table : List[Dict]):
- try:
- connection = sqlite3.connect("database.db")
- cursor = connection.cursor()
- cursor.execute(f"PRAGMA table_info{table_name}")
- columns = [column[1] for column in cursor.fetchall()]
- for item in table:
- placeholders = ', '.join(['?'] * len(columns))
- query = f"INSERT INTO {table_name} ({', '.join(columns)}) VALUES (){placeholders}"
- data_values = [item.get(column) for column in columns]
- cursor.execute(query, data_values)
- connection.commit()
- connection.close()
- except sqlite3.Error as e:
- print(f"Error occured: {e}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement