Till KTH:s startsida Till KTH:s startsida

Advanced assignment

Interfacing to SQLite from Python

Completing this assignment will raise your grade one step.

The purpose of this assignment is to practice using an SQL database from Python. By mastering this, which is not very hard, you have learned a great way of easily saving and accessing data. Moreover, you have immediate access to very advanced data manipulation.

Your task is to solve the exercises in "Your own database" using a Python program instead of using pure SQL interactively.

Use the standard Python module sqlite3 and write a program that, when called from the command line, solves the tasks. The output from the program should be clearly printed and tabulated to stdout. Simply "echoing" the result from a select is not sufficient; you must show that you can extract columns of data from a SELECT command to be ready to process it in some way.

To present:

  1. Your Python program, code and test runs
  2. How do you extract the data from the results of SELECT commands?
  3. What happens when you insert Sus scrofa a second time?

Lars Arvestad skapade sidan 2 november 2015

Lärare Lars Arvestad ändrade rättigheterna 30 november 2015

Kan därmed läsas av alla och ändras av lärare.
kommenterade 17 december 2015

I keep getting the error: sqlite3.DatabaseError: file is encrypted or is not a database, when I try to query the protdb.sqlite3 file with the sqlite3 module. This happens on my computer as well as the CSC computers. Has anyone encountered this and knows what's up?

Lärare kommenterade 17 december 2015

When you test no the school computers, have you tried to access the data file directly, from /info/appbio10/data/protdb.sqlite3 ?

Lärare kommenterade 17 december 2015

I am getting the same error when I open the database into sqlite3, but it works fine if I 'read' it. (with command ".read" in sqlite3).

kommenterade 17 december 2015

I managed to do 'Your own database' with sqlite3 just fine without any error, but using this code in python for the same database file:

#!/usr/bin/python

import sqlite3 as lite

con = lite.connect('protdb.sqlite3') #on my own computer
cur = con.cursor()

for row in cur.execute('SELECT * FROM species;'):
     print row #indented

returns this error, and I always connect to the file directly on the school computers. 

Lärare kommenterade 17 december 2015

I have set up a database which should work: /info/DD2404/appbio15/data/protdb2.sqlite3

kommenterade 17 december 2015

Great, do you have an online version?

Lärare kommenterade 17 december 2015

This link will live for 5 days: https://transfer.sh/11dlbr/p.db

kommenterade 17 december 2015

This seems to work, thanks!