What I am trying to do is create a single line of code to execute sql that inserts data into whichever table the user decides. Each table will have a varying number of columns therefore I cannot specify how many ?s to put in the brackets. If anyone can find a solution, please share it with me as I am stuck as of now.
self.conn.execute('INSERT INTO ' self.table ' VALUES (?)', (self.data))
self.data is a list containing 3 items as of now but may change if the table is changed.
CodePudding user response:
You could dynamically generate a string of comma-separated ?
based on the length of self.data
, e.g.:
values = ", ".join("?" * len(self.data))
self.conn.execute('INSERT INTO ' self.table ' VALUES (' values ')', (self.data))
If you have Python 3.6 or later, using a formatted string with execute()
would be more Pythonic and compact:
self.conn.execute(f'INSERT INTO {self.table} VALUES ({values})', (self.data))