10

I know this is simple but I can't get it working! I have no probs with insert,update or select commands, Lets say I have a dictionary and I want to populate a table with the column names in the dictionary what is wrong with my one line where I add a column?

##create
con = sqlite3.connect('linksauthor.db')
c = con.cursor()
c.execute('''create table linksauthor (links text)''')
con.commit()
c.close()
##populate author columns
allauthors={'joe':1,'bla':2,'mo':3}
con = sqlite3.connect('linksauthor.db')
c = con.cursor()
for author in allauthors:
    print author
    print type(author)
    c.execute("alter table linksauthor add column '%s' 'float'")%author  ##what is wrong here?
    con.commit()
c.close()

4 Answers 4

18

Your paren is misplaced. You probably meant this:

c.execute("alter table linksauthor add column '%s' 'float'" % author)
Sign up to request clarification or add additional context in comments.

Comments

3

You are also using strings for the column name and type name. Sqlite is very forgiving, but you really should be using double-quotes as the quoting character for identifiers.

Comments

1

Here is another option:

c.execute(
f"""
ALTER TABLE linksauthor 
ADD COLUMN {author} 'float'
""")

Comments

0

The other answers are suggesting Python's built-in string manipulation which is insecure and can lead to SQL injection. I recommend the DB-API’s parameter substitution: https://docs.python.org/3/library/sqlite3.html?highlight=parameter%20substitution

c.execute("alter table linksauthor add column (?) 'float'", (author,))

2 Comments

This unfortunately gives OperationalError: near "(": syntax error, though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.