0

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.

3
  • Show real code. my_id = tablename is clearly invalid; where is tablename coming from? Commented Jun 30, 2016 at 8:13
  • Hi Daniel Roseman, tablename is obtained in the '2nd loop' - sorry forgot to add single quotes, I added it in directly so not to over complicate the code. The '2nd loop' basically opens and reads an XML file and grabs certain XML element values as variable names and list values, 'tablename' is one of these elements, but I simplified the collection of this variable for this post. Commented Jun 30, 2016 at 8:38
  • Your misuse of try/except hides the actual error. Commented Jun 30, 2016 at 12:06

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.