Wednesday, January 27, 2010

Connect to a SQLite database using python

SQLite is included since python 2.5 I connected to a SQLite database created from zotero that way:

import sqlite3 as sqlite
con = sqlite.connect('zotero.sqlite')
cur = con.cursor()
cur.execute('CREATE TABLE foo (o_id INTEGER PRIMARY KEY, fruit VARCHAR(20), veges VARCHAR(30))')
con.commit()
cur.execute('INSERT INTO foo (o_id, fruit, veges) VALUES(NULL, "apple", "broccoli")')
con.commit()
print cur.lastrowid

cur.execute('SELECT * FROM foo')
print cur.fetchall()

Here is the output:
>pythonw -u "test_sqlite.py"
1
[(1, u'apple', u'broccoli')]
2

With help from DZone snippets and devshed. However devsched's information about downloading and building the sqlite library is outdated as it is now included in python.


Edit:
In a later post, I explain how to connect do an SQLite database with the R statistical software and a package called dplyr.

1 comment:

Tanmay said...

Thanks a lot