So I wanted to create a function, that take a dictionary and update the database based on the key/values pairs on that dictionary.
My main problem is that I have tables of different row sizes, so my dictionaries will have also different sized I am not sure how to handle that. for example
table 1: date | id | startDate | firmwareVersion | location | lastUpdate|
list 1: {date :1583171545,id : 22, startDate 1582131612, firmwareVersion: 1.7, location: "A", lastUpdate: 1583051569, },{date :1583171545,id : 32, startDate 1582131452, firmwareVersion: 1.6, location: "B", lastUpdate: 1583051569, }
table 2: date | error|
list 2: {date: 1583171545, error: "whateverError" }
I am not speaking about the size of data in each row but the number of rows is different.
Here is my function, how can I change it to handle updating both table 1 or 2 regardless of which one is passed to it.
def my_function(table, table_name):
cursor.execute(f"INSERT INTO {table_name} () VALUES ()")
my_function(sensorstable, "sensorstable")
, also passe the name of the table, but ideally I wish I could use the variable name as the table name. for example:
if my dictionary is saved into a variable deviceList
, I would want to use deviceList
as the database name.
you can do something simple like this
{date :1583171545,id : 22, startDate 1582131612, firmwareVersion: 1.7, location: "A", lastUpdate: 1583051569, },{date :1583171545,id : 32, startDate 1582131452, firmwareVersion: 1.6, location: "B", lastUpdate: 1583051569, }
def update_table_last_valid_value(table, table_name):
column_values = []
if table:
column_keys = list(table.keys())
column_keys = ", ".join(column_keys)
for key, value in table.items():
column_values.append(value)
cursor.execute(f"INSERT INTO {table_name} ({column_keys}) VALUES {tuple(column_values)};")
cursor.close()
return result
of course this is assuming you have just one row as it seems like it's the case, otherwise you might wanna tweak it a little bit