Using Python 3 and sqlite3 I am looking to create several databases in a loop based on a varying number of columns (from a list).
Here's my code:
# Main loop here
# Initialize lists to populate - including SQL Primary auto-increment key
parameter_hdrs = ['a INTEGER PRIMARY KEY']
parameter_defaults = ['NULL']
# 2nd Loop here to read a file and populate list with column headers and drop into 'parameter_hdrs' list
# 2nd Loop also here to gather some 'default' values and drop into 'parameter_defaults' list
conn = sqlite3.connect(name+".db")
cursor = conn.cursor()
my_id = 'tablename' # created each time from loop
# Attempt at creating new database using columns in parameter_hdrs list
try:
hdr_string = ', '.join('?' * len(parameter_hdrs))
query_string = "CREATE TABLE "+my_id+" (%s);" parameter_hdrs
print(query_string)
cursor.execute(query_string)
except sqlite3.OperationalError:
print('Database already exists')
# Attempt to add values from 'parameter_defaults' list to above database
val_string = ', '.join('?' * len(parameter_defaults))
val_query_string = "INSERT INTO "+my_id+" VALUES (%s);" % val_string
cursor.execute(val_query_string, parameter_defaults)
# Continues Main loop
When I run the script I get the following output (also includes printed query_string):
Traceback (most recent call last):
CREATE TABLE tablename (?, ?, ?, ?, ?, ?, ?); # query_string here
File "C:/myscript.py", line 72, in <module>
cursor.execute(val_query_string, parameter_defaults)
sqlite3.OperationalError: no such table: tablename
I can see the database created, but the 'Insert into' section doesn't seem to like or recognize the table name from the 'Create table' section.
Any pointers into solving this would be great, thanks.
my_id = tablenameis clearly invalid; where istablenamecoming from?try/excepthides the actual error.