CREATE TABLE PRODUCTS ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT (30), price FLOAT, qty INTEGER );
1 iPad Air 60000 10 2 Google Pixel 55000 5 3 Samsung Note 8 50000 2 4 iPhone 14 Pro 120000 3 5 AirPods 3rd Gen 20000 5
# Convert PRODUCTS table to an array of JSON objects and write them to products.json import sqlite3 import json # Convert tuple with product details to dict def product_row_to_dict(product): return {"id": product[0], "name": product[1], "price": product[2], "qty": product[3]} products = [] con = sqlite3.connect(r"c:\dev\python\test.db") # Connect to database - test.db cur = con.cursor() cur.execute("select * from products") # retrieve all products from table for product in cur.fetchall(): products.append(product_row_to_dict(product)) # convert tuple to dict and add to list cur.close() con.close() # Write to file f = open("products.json", "wt") json.dump(products, f) # converts list of dict to array of JSON and writes it to products.json f.close()
[ {"id": 1, "name": "iPad Air", "price": 60000.0, "qty": 10}, {"id": 2, "name": "Google Pixel", "price": 55000.0, "qty": 5}, {"id": 3, "name": "Samsung Note 8", "price": 50000.0, "qty": 2}, {"id": 4, "name": "iPhone 14 Pro", "price": 120000.0, "qty": 3}, {"id": 5, "name": "AirPods 3rd Gen", "price": 20000.0, "qty": 5} ]
[ {"name": "Logi MX Master 3", "price": 15000.0, "qty": 3}, {"name": "Seagate 2 TB External Disk", "price": 5500, "qty": 1} ]
# Load data from JSON file to PRODUCTS table import sqlite3 import json f = open("newproducts.json", "rt") # Convert array of JSON objects to list of dict using load() # Each product is represented by a dict products = json.load(f) f.close() con = sqlite3.connect(r"c:\dev\python\test.db") cur = con.cursor() count = 0 # take one dict at a time from list for product in products: try: # insert a row cur.execute("insert into products(name,price,qty) values(?,?,?)", (product['name'], product['price'], product['qty'])) count += 1 except Exception as ex: print("Error : ", ex) # make insertions permanent con.commit() cur.close() con.close() print(f"Inserted {count} products") # Display how many rows were inserted