0

Say I have 100 different integers I want to store like a row with 100 columns.

I am trying it like this:

db = sqlite3.connect("test.db")
c = db.cursor()
c.execute('''
    CREATE TABLE IF NOT EXISTS nums(
        id INTEGER PRIMARY KEY, 
''')
for i in range(100):
    c.execute('''
    ALTER TABLE nums
    ADD ''' + 'column_' + i + '''INTEGER''')

db.commit()

Someone told me that when you are using numbers as column names you could probably do it a better way. But if I for example have a list with strings in python, and I want to loop through them and store every individual string in its own column, the approach would be the same, right?

However, this code runs without errors for me, but no new table is created, how come?

3
  • 1
    Remove the , after id INTEGER PRIMARY KEY. Commented Jan 2, 2021 at 12:36
  • Also you need a space between i and INTEGER in your ATLER statement Commented Jan 2, 2021 at 12:52
  • 1
    "Someone" is absolutely right. If you have a set of names created by a number sequence, you are probably not following best practices. But in your cases the problem sits a little deeper: the wrong approach is in your own requirements already: "I want to […] store every individual string in its own column". Commented Jan 2, 2021 at 12:56

1 Answer 1

1

Your ALTER statement is incorrect as it's missing the COLUMN after ADD. You can use the following:

for i in range(100):
    c.execute(f'ALTER TABLE nums ADD COLUMN column_{i} INTEGER')
Sign up to request clarification or add additional context in comments.

Comments

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.