I'm planning on making a function that when given a list and table name, it will insert the values of the list into the table. I know the maximum number of columns a table will have (for example sake let's say it's 4).
So I'd have
list = [col1, val1, col2, val2, col3, val3, col4, val4]
stmt = 'INSERT INTO {} ({}, {}, {}, {}) VALUES {}, {}, {}, {};'.format('myTable', list[0], list[1], list[2], list[3], list[4], list[5], list[6], list[7], list[8])
cur.execute(stmt)
but say for example another table only has two columns. Then if stmt = 'INSERT INTO {} ({}, {}, {}, {}) VALUES ({}, {}, {}, {});'.format('myTable', list[0], list[1], list[2], list[3], list[4], list[5], list[6], list[7], list[8])
were in a function the program would crash as list[7]
and [list8]
would be out of bounds! (see what I'm saying?)
In the example I have a simple list but currently the program has a list inside a list of the format [[val1, colName1], [val2, colName2],...,[valn, colNamen]]
where vali
is the value to go into coli
and all of this will be on the same row in a table.
The problem is made more complicated because a value to be inserted may have experienced an error and be NoneType
. Since you can't insert a null into Postgres, this would be an issue.