0

my question is, as the title says, how I can create a variable column in SQL lite used in Pyhton.

Here's my code, to show you what exactly I mean:

#Table with variables
def dynamic_data_entry(list_name, num, column):
    element_name = list_name[num]
    cur.execute("INSERT INTO myliltable (column) VALUES (?)", element_name)
    con.commit()

I want to insert the column name, when I call the function, so I can use the function for more than one column, but I keep getting an error, that the column 'column' doesn't exist. Is there another way to do this, so I can change set the column name when I call the function, or just change the SQL part.

If there is a thread about this already, I would appreciate it, if you could link it, so I can read it myself (I couldn't find anything similar to this topic yet, which worked).

Thanks in advance, I appreciate your help

1 Answer 1

3

You need to use the string's format() method to insert the column name into the SQL string:

cur.execute("INSERT INTO myliltable ({}) VALUES (?)".format(column),
            element_name)

You can find more information in the Python docs.

Sign up to request clarification or add additional context in comments.

1 Comment

Would this introduce any type of security flaw as the official python sqlite3 documentation says not to use string methods in sql statements. Although, as long as this is not a variable accessible to the end user, it might not have the same type of security implications. Is my understanding correct?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.