Python                                                          Home : www.sharetechnote.com

 

 

 

 

Python - SQLite

 

NOTE 1 : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x

NOTE 2 : All the examples in this page are assumed to be written/run on Windows 7 unless specifically mentioned. You MAY (or may not) need to modify the syntax a little bit if you are running on other operating system.

 

 

 

Where is SQLite ?

 

If you are using a relatively recent version of Python, SQLite would be included in the installation folder as shown below (I am using Python 3.6 for this example)

 

 

 

You can get the sqlite dll and sqlite command line tools from following sites if you want to install on your own.

 

 

 

Basic Command Test

 

import sqlite3

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

 

c = conn.cursor()

 

# Delete the table if it is already exists. I put this so that the sample DB is always created new.

# In real life, it would be less likely to do this operation.

c.execute('''DROP TABLE IF EXISTS phoneBook''')

 

# Create table

c.execute('''CREATE TABLE phoneBook (contactID INTEGER PRIMARY KEY, LastName TEXT, FirstName TEXT, PhoneNumber TEXT)''')

 

# Insert a row of data

c.execute('''INSERT INTO phoneBook(LastName,FirstName,PhoneNumber) VALUES ('Benjamin','Smith','123-4567')''')

c.execute('''INSERT INTO phoneBook(LastName,FirstName,PhoneNumber) VALUES ('Jacob','John','123-8421')''')

c.execute('''INSERT INTO phoneBook(LastName,FirstName,PhoneNumber) VALUES ('Robert','Williams','456-1234')''')

 

# Save (commit) the changes

conn.commit()

 

# Query Data

c.execute('''SELECT * FROM phoneBook''')

retrievedData = c.fetchall();

 

# Print Result

for r in retrievedData :

   print(r)

 

# Close the connection

conn.close()

 

 

Result :----------------------------------------------------

 

(1, 'Benjamin', 'Smith', '123-4567')

(2, 'Jacob', 'John', '123-8421')

(3, 'Robert', 'Williams', '456-1234')

 

 

 

SELECT *

 

NOTE : The database file used in this example is from http://www.sqlitetutorial.net/sqlite-sample-database/  and you can see the structure of the whole database in this page. The database file name is chinook.db and you should put the file into the same folder as the python script you run.

 

 

Example 01 > 'tracks' table

 

import sqlite3

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

 

c = conn.cursor()

 

# Query Data

c.execute('''SELECT * FROM tracks''')

retrievedData = c.fetchall();

 

# Print Result. Printing out the whole data is too much. So I restricted the range of the print to a small segment

# just to show that some data are retrieved from the table.

for r in retrievedData[0:9] :

   print(r[0:5])

 

 

conn.close()

 

 

Result :-------------------------------

 

(1, 'For Those About To Rock (We Salute You)', 1, 1, 1)

(2, 'Balls to the Wall', 2, 2, 1)

(3, 'Fast As a Shark', 3, 2, 1)

(4, 'Restless and Wild', 3, 2, 1)

(5, 'Princess of the Dawn', 3, 2, 1)

(6, 'Put The Finger On You', 1, 1, 1)

(7, "Let's Get It Up", 1, 1, 1)

(8, 'Inject The Venom', 1, 1, 1)

(9, 'Snowballed', 1, 1, 1)

 

 

Example 02 > 'media_types' table

 

import sqlite3

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

 

c = conn.cursor()

 

# Query Data

c.execute('''SELECT * FROM media_types''')

retrievedData = c.fetchall();

 

# Print Result

for r in retrievedData :

   print(r)

 

 

conn.close()

 

 

Result :-------------------------------

 

(1, 'MPEG audio file')

(2, 'Protected AAC audio file')

(3, 'Protected MPEG-4 video file')

(4, 'Purchased AAC audio file')

(5, 'AAC audio file')

 

 

 

SELECT *  WHERE

 

NOTE : The database file used in this example is from http://www.sqlitetutorial.net/sqlite-sample-database/  and you can see the structure of the whole database in this page. The database file name is chinook.db and you should put the file into the same folder as the python script you run.

 

 

Example 01 > 'tracks' table

 

import sqlite3

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

 

c = conn.cursor()

 

# Query Data

c.execute('''SELECT * FROM tracks WHERE MediaTypeId=4''')

retrievedData = c.fetchall();

 

# Print Result. Printing out the whole data is too much. So I restricted the range of the print to a small segment

# just to show that some data are retrieved from the table.

for r in retrievedData :

   print(r[0:4])

 

 

conn.close()

 

 

Result :-------------------------------

 

(3336, 'War Pigs', 260, 4)

(3414, 'Symphony No. 104 in D Major "London": IV. Finale: Spiritoso', 283, 4)

(3452, 'SCRIABIN: Prelude in B Major, Op. 11, No. 11', 318, 4)

(3479, 'Prometheus Overture, Op. 43', 324, 4)

(3480, 'Sonata for Solo Violin: IV: Presto', 325, 4)

(3496, 'Étude 1, In C Major - Preludio (Presto) - Liszt', 340, 4)

(3498, 'Concerto for Violin, Strings and Continuo in G Major, Op. 3, No. 9: I. Allegro', 342, 4)

 

 

 

(INNER) JOIN

 

NOTE : The database file used in this example is from http://www.sqlitetutorial.net/sqlite-sample-database/  and you can see the structure of the whole database in this page. The database file name is chinook.db and you should put the file into the same folder as the python script you run.

 

 

Example 01 > 'tracks' table and 'media_types' table

 

 

import sqlite3

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

 

c = conn.cursor()

 

# Query Data

c.execute('''SELECT TrackId,[tracks].Name,[media_types].Name FROM tracks JOIN media_types

                                                                         ON [tracks].MediaTypeId=[media_types].MediaTypeId''')

retrievedData = c.fetchall();

 

# Print Result. Printing out the whole data is too much. So I restricted the range of the print to a small segment

# just to show that some data are retrieved from the table.

for r in retrievedData[0:10] :

   print(r)

 

 

conn.close()

 

 

Result :-------------------------------

 

(1, 'For Those About To Rock (We Salute You)', 'MPEG audio file')

(6, 'Put The Finger On You', 'MPEG audio file')

(7, "Let's Get It Up", 'MPEG audio file')

(8, 'Inject The Venom', 'MPEG audio file')

(9, 'Snowballed', 'MPEG audio file')

(10, 'Evil Walks', 'MPEG audio file')

(11, 'C.O.D.', 'MPEG audio file')

(12, 'Breaking The Rules', 'MPEG audio file')

(13, 'Night Of The Long Knives', 'MPEG audio file')

(14, 'Spellbound', 'MPEG audio file')