Python tutorial-Fetch sata from SQLite database


Fetch data from SQLite database


Now you know how to connect to database, create cursor object, and its useful methods and attributes. Next, we will retrieve data from the database by using fetchxxx() method of the cursor object.
import sqlite3
conn = sqlite3.connect('customerlist.db')
curs = conn.cursor()
query = 'SELECT * FROM tblcustomerlist'
curs.execute(query)
for row in curs.fetchall():
            print row[0],"  ",row[1],"  ",row[2],"  ", row[3]  
If you want to filter data based on a condition, you can supply parameters to sql statements.
import sqlite3
conn = sqlite3.connect('customerlist.db')
curs = conn.cursor()
name='Dara Yuk'
curs.execute("SELECT * FROM tblcustomerlist where Name=:who",{"who":name})
for row in curs.fetchall():
            print '%-20s%-25s%-20s%s' % (row[0],row[1],row[2],row[3])
 
Note: who is a parameter and name is its value


Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.