I want to add new data entries, in the json format, into a database using sqlite3. The example database 'test.db' has a table 'cars' that takes 3 values, 'MAKE', 'MODEL' and 'COST'. The new data contains entries with missing name/value pairs:
entries = {
"CARS":[
{
"MAKE": "VW",
"MODEL":"Passat",
"COST":23000
},
{
"MAKE":"Honda",
"MODEL":"Civic"
}
]
}
To get around the KeyError raising, I used setdefault() and added key/None pairs if they are missing in each entry:
import sqlite3
keys = ["MAKE", "MODEL", "COST"]
with sqlite3.connect("test.db") as conn:
c = conn.cursor()
for car in entries['CARS']:
for key in keys:
car.setdefault(key, None)
c.execute('INSERT INTO cars VALUES(?,?,?)', (car['MAKE'], car['MODEL'], car['COST']))
Although this seems to work, is there also a way to add entries with missing name/value pairs by using the SQL syntax?
collections.defaultdict(lambda : None).setdefault(), how aboutc.execute("...", (car.get("MAKE"), car.get("MODEL", car.get("COST"))). Sincedict.getreturnsNoneif the key isn't found, this should do just what you want.