2

I am trying to create automatically a rather large sqlite database tables which all have at least 50 columns. The column names are already available in different lists. Using the .format I almost did this. The only open issue is the predetermination of the number of placeholders for "{}" from the length of name's list. Please see the code example below.

import sqlite3

db_path = "//Some path/"
sqlite_file = 'index_db.sqlite'

conn = sqlite3.connect(db_path + sqlite_file)
c = conn.cursor()

db_columns=['c1','c2','c3','c4','c5']

#This code is working
c.execute("create table my_table1 ({}, {}, {}, {}, {})" .format(*db_columns))
#This code doesn't work
c.execute("create table my_table2 (" + ("{}, " * 5)[:-2] + ")" .format(*db_columns))
#Following error appears
OperationalError: unrecognized token: "{"

#--> This even that the curly brackets are the same as in my_table1 
print("create table my_table2 (" + ("{}, " * 5)[:-2] + ")") 
#Output: create table my_table2 ({}, {}, {}, {}, {})

c.execute("INSERT INTO my_table1 VALUES (?,?,?,?,?)", (11, 111, 111, 1111, 11111))

conn.commit()
c.close
conn.close()

Is there a way to resolve that issue for my_table2? Or is there a better way to create the column names dynamically from a list?

P.s. This is an internal database so I don't have any concerns regarding security issues due to using variables as names dynamically.

Thanks in advance! Timur

Timur S
  • 21
  • 1
  • 2

1 Answers1

1

Disclaimer:

do not use string concattenation to build SQL-strings - see f.e. http://bobby-tables.com/python for how to avoid injection by using parametrized queries.


According to this old post: Variable table name in sqlite you can not use "normal" parametrized queries to create a table / columnnames.

You can pre-format your createstatement though:

def scrub(table_name):
    # attributation: https://stackoverflow.com/a/3247553/7505395
    return ''.join( chr for chr in table_name if chr.isalnum() )

def createCreateStatement(tableName, columns):
    return f"create table {scrub(tableName)} ({columns[0]}" + (
            ",{} "*(len(columns)-1)).format(*map(scrub,columns[1:])) + ")"

tabName = "demo"
colNames = ["one", "two", "three", "dont do this"]

print(createCreateStatement(tabName, colNames))

Output:

create table demo (one,two ,three ,dontdothis )

The scrub method is taken from Donald Miner's answer - upvote him :) if you like

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69