Friday, July 15, 2011

Accessing a file with SQLite3 using python

Before experimenting with this problem, we need to install SQLite first. Type the following command in terminal.

sudo apt-get install sqlite3

After installing it, we can test it by typing import sqlite3 in python interactive window. 

Now come to our problem. We need to create a text file in which name, age and mark of a list of students are already saved. Our requirement is to write a python program which stores the name, age and mark from the text file to a table in the SQLite3 database.

We need to import sqlite3 module to work this program correctly. A database is created first, say ajay.db.

conn = sqlite3.connect('ajay.db')

Then create  a table t1 in that database.

curs.execute('''create table t1(name varchar2(25), age integer, mark integer)''')

curs is the object that connects with the database ajay.db. it can create by following code,

curs = conn.cursor()

Then open the text file and split it and save each name, age and mark as lists and save it to a dictionary like {[name1,age1,mark1],[name2,age2,mark2] ...... }.

After that we need to enter them to the table t1.

curs.execute('''insert into t1 values(?,?,?)''',dic[item])

This is the code used for that. Then commit that transaction. Then finish it by writing the main function. When we run this code we need to write the command as,

python a.text

The a.text is the argument we are passing and that text file contains the list of details that is required to save in the table t1. You can download the source code of this problem which includes and a.text by clicking hereExperiment on it.



No comments:

Post a Comment