Friday, April 11, 2008

Create and manipulate SQLite databases using Python

SQLite is a small,embedable relational database management System which is almost ACID compliant. It is 
heavily used in the Free/Open source world and by people like Apple. It is deployed in Firefox, Mac OS X, Skype, IPhone 
and Symbian phones. So when you use your Nokia phone (a symbian based phone), remember that you are a sqlite user. With a size less than 500k, it is one of the small but beautiful softwares which is platform independent.

Now let’s play with sqlite3 in Linux..

To create a sqlite database (here test.db), run the sqlite3 command in terminal.

sqlite3 test.db “create table t1(t1key INTEGER PRIMARY KEY, data TEXT, num double, timeEnter Date);”

now we have the test.db database in the present working directory.

To see the table details in a given database, execute this command.

sqlite3 test.db “.table”
t1

Now let’s populate the database..
sqlite3 test.db “insert into t1(data,num) values(’this is a sample data’,3);”

Ok, now let’s use python’s sqlite bindings to manipulate the database and the data in it..

>>> import sqlite
>>> con = sqlite.connect(’test.db’)
>>> cur = con.cursor()
>>> cur.execute(’insert into t1(data,num) values(“this is again a test”,1)’)
>>> cur.commit()
>>> cur.execute(’SELECT * from t1′)
>>> print cur.fetchall()
[(1, 'this is a sample data', 3.0, None), (2, 'this is again a test', 1.0, None)]

>> cur.execute(’select * from t1 where num=3′)
>>result=cur.fetchall()[0]
>>print result
(1, ‘this is a sample data’, 3.0, None)
>> print result[1]
this is a sample data

Well, if you think it is not enough to use sqlite in your project, refer this SQLite tutorial : http://souptonuts.sourceforge.net/readme_sqlite_tutorial.html

Posted by maxinbjohn in 05:45:50
Comments

Leave a Reply