First pySQLite Application

From Superk

Jump to: navigation, search

This is my first attempt at writing Python code. It also happens to be my first adventure with SQLite.

#!/usr/bin/env python

import sys, string
import sqlite

'''Create a connection object to the DB'''
con = sqlite.connect('mydb.db', autocommit=1)
cur = con.cursor()

def getAll() :
    '''Select all records from the DB'''
    try :
        '''Try and get records from the DB'''
        cur.execute('SELECT * FROM foo')
        res = cur.fetchall()
        return res
    except :
        '''If there is no table to draw records from, create the table'''
        print 'Creating a new table in the DB since one doesn\'t exist yet.'
        cur.execute('CREATE TABLE foo (id INTEGER PRIMARY KEY, fruit VARCHAR(20), descr VARCHAR(50))')
        getAll()

def fileExists(f) :
    '''Checks if the provided file exists (not used yet)'''
    try :
        file = open(f)
    except IOError :
        exists = 0
    else :
        exists = 1
    return exists

def getLast() :
    '''Gets the last record from the DB if there is one'''
    if len(getAll()) > 0 :
        print 'The last record was:\n', getAll()[-1]
        print 'There are %s records in the DB.' % len(getAll())
    else :
        print 'No records in the DB'

def insItem(name,desc) :
    '''Inserts an item into the DB'''
    insstr = 'INSERT INTO foo (id,fruit, descr) VALUES(NULL, %s, %s)'
    cur.execute(insstr, name, desc)
        
def newInput() :
    '''Get input from the user for the new record'''
    f = raw_input('Enter a fruit: ')
    d = raw_input('Describe the fruit: ')
    insItem(f,d)

def main() :
    '''Define "a" to default to "y" '''
    a = 'y'
    
    while a == 'y' :
        '''While the user continues to answer affirmatively, run the program'''
        getLast()
        newInput()
        a = raw_input('Enter another? (y/n): ')
    else :
        '''If the user answers negatively, quit the program'''
        quit

if __name__ == "__main__" :
    main()

This is what it looks like when you run it:

mycomputer:~/ $ ./sql.py
No records in the DB
Enter a fruit: Strawberry
Describe the fruit: Sometimes the seeds stick in your teeth
Enter another? (y/n): y
The last record was:
(1, 'Strawberry', 'Sometimes the seeds stick in your teeth')
There are 1 records in the DB.
Enter a fruit: 
Personal tools