Accessing SQLite from a program 1. Download me! Place mydata.db in the folder e.g z:\db\ >>> import sqlite3 >>> db = sqlite3.connect(name of database file) EXAMPLE : >>> cursor = db.cursor() >>> cursor.execute(command) # replace with SQL command string >>> yr = '2002' >>> query = '''SELECT M.name,M.year
FROM Movie M, Person P
WHERE M.id=P.id AND year = ?;'''
The above query is a parameterised query and can be executed as follows: >>> cursor.execute(query, [yr]) >>> cursor.fetchone() for tuple in cursor: >>> db.rollback() >>> db.commit() >>> db.close() File Processing Opening (& closing!!!) a file <file-handle> = open(<filename>, <mode>)
<file-handle>.close() Now, practice writing in a file: >>>
fh = open('z:/db/temp.txt', 'w') Check out the new file!!! Why is the second line of the file second and not first? Example
1. Download me! Place mydata.db in the folder e.g z:\db\ 2. Open a new module file called getMovies.py and begin with the following lines: >>> import sqlite3 >>> db = sqlite3.connect('z:\db\mydata.db') 3. Initialize a cursor object >>> cursor = db.cursor() You are connected and you have a cursor object!! You are ready to perform queries! 4. Now, we perform the necessary actions to print one by one the attributes in the result of the query. Write a query to find the name and duration of all Steven Spielberg films ? 5. Execute it: >>> cursor.execute(query) 6. Print results on the screen: Result: Jaws ... 124 7. Now let's modify the file to allow the user to enter the name of the director. Use a parameterized query! 8. We will now write the result to a file! Let 's also modify it to print a message if the director is not found. >>> fh = open('z:\db\spielberg.txt', 'w') 9. Write using a for loop! Hint: First create the line you want to write (i.e. line = str(tuple[0]) +...+...+"\n" and then use fh.write to write it!) 10. Close the file handle!!!!!!!! (otherwise nothing will be written in the file!) |
|||||