Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add columns to sqlite3 python?

Tags:

python

sqlite

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()
like image 356
user291071 Avatar asked Apr 22 '10 18:04

user291071


People also ask

How do I add multiple columns in SQLite?

How do I add multiple columns in SQLite? SQLite does not support adding multiple columns to a table using a single statement. To add multiple columns to a table, you must execute multiple ALTER TABLE ADD COLUMN statements.

How do I add data to SQLite in Python?

Inserting data using pythonImport sqlite3 package. Create a connection object using the connect() method by passing the name of the database as a parameter to it. The cursor() method returns a cursor object using which you can communicate with SQLite3.


2 Answers

Your paren is misplaced. You probably meant this:

c.execute("alter table linksauthor add column '%s' 'float'" % author)
like image 63
balpha Avatar answered Nov 03 '22 04:11

balpha


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.

like image 24
Frank Krueger Avatar answered Nov 03 '22 03:11

Frank Krueger