The python – sqlite3 module


Learnt to use python module sqlite3. Its actually quite simple. If one knows the way to use sqlite3 using the shell, then using it in python is a piece of cake.

First of all, you need to import the sqlite3 module:
import sqlite3
Now, you need a Connection object to represent the database:
conn = sqlite3.connect('example.db')
When you are done with creating the connection object, you will need another Cursor object:
c = conn.cursor()
Tables can be created by :
c.execute('''CREATE TABLE table1
             ( col1 , col2 , col3 )''')

Note, table1 is the name of the table and col1, col2, col3 are the respective columns.

Inserting data into the table :
c.execute('INSERT INTO table1 VALUES ('abc' , 'mno' , 'xyz')')
Data can also be feeded into the tables using tuples. This one comes in handy during program execution :
t = ( 'abc' , 'mno' , 'xyz' ) # t is a tuple
c.execute('INSERT INTO table1 VALUES (?,?,?)', t)
After you are done with entering data, commit the changes :
And close the database :

The database was saved with the name “example.db”  in the current working directory.

To print the data stored in the database,
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
for row in c.execute('SELECT * FROM table1):
    print row

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s