1

Iam new to python sqlite, and I have a problem with create table query.

I need to create a table, but I have the column names of the table as a list.

columnslist = ["column1", "column2", "column3"]

Now, I have to create a table MyTable with the above columns. But the problem is, I won't know before hand how may columns are there in columnslist

Is it possible to create a table with the number of and name of columns given in columnslist and its syntax?

2
  • 1
    len(columnslist) gives you the length. Commented Jul 1, 2015 at 7:30
  • len(columnslist) is a number of names in list. columnslist[0]...columnslist[x]...columnslist[len(columnslist)-1] are names of particular list element Commented Jul 1, 2015 at 7:33

1 Answer 1

1

You can first convert your list to tuple and use str.format:

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE table_name {}'''.format(tuple(column_list)))
Sign up to request clarification or add additional context in comments.

2 Comments

Wow!! It never occured to me to use string format. Thanks a lot!
this is fantastic, you saved my day

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.