python for database access and event driven programming in python

49
Python for database access and Event driven programming in Python

Upload: yori

Post on 23-Feb-2016

36 views

Category:

Documents


5 download

DESCRIPTION

Python for database access and Event driven programming in Python. Database access in Python. A set of tutorials, including access to MySQL and PostgreSQL http://python.about.com/od/pythonanddatabases/Connecting_to_Databases_With_Python.htm A brief introduction to SQLite3 - PowerPoint PPT Presentation

TRANSCRIPT

Event driven programming in Python

Python for database access and Event driven programming in PythonDatabase access in PythonA set of tutorials, including access to MySQL and PostgreSQLhttp://python.about.com/od/pythonanddatabases/Connecting_to_Databases_With_Python.htm

A brief introduction to SQLite3Lightweight disk-based databaseSee http://docs.python.org/library/sqlite3.htmlNOTE: There are many details of database access. Here we will do a brief example and establish the ability to do the basic operations. See this website for a complete list of featuresSQL3litehttp://docs.python.org/2/library/sqlite3.html

import sqlite3conn = sqlite3.connect('sample.db')c=conn.cursor()#Create tablec.execute('''CREATE TABLE stocks (date text, trans text, symbol text, \ qty real, price real)''')#Insert a row of datac.execute("INSERT INTO stocks VALUES \('2006-01-05','BUY','RHAT',100,35.14)")#Save (commit) the changesconn.commit()#Close the connection. #Be sure the changes are committed first.conn.close()New database (sample.db) created with one row of dataAccess the dataimport sqlite3cnx = sqlite3.connect('sample.db')c = cnx.cursor()

t = ('RHAT',)c.execute('SELECT * FROM stocks WHERE symbol=?', t)print c.fetchone()print '======================\n'

# Larger example that inserts many records at a timepurchases = [('2006-03-28','BUY', 'IBM', 1000, 45.00), ('2006-04-05','BUY', 'MSFT', 1000, 72.00), ('2006-04-06','SELL', 'IBM', 500, 53.00), ]c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)for row in c.execute('SELECT * FROM stocks ORDER BY \ price'): print rowOutput(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14)======================

(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14)(u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0)(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)(u'2006-04-05', u'BUY', u'MSFT', 1000.0, 72.0)The first entry in the last set came from the original values in the db, from the program that created the db.Another sqllite3 exampleFirst, import sqlite3Create an object that represents the databaseUse standard sqlThis example from Nakul Rathodimport sqlite3def main(): db = sqlite3.connect('test.db') # connect to the database or create the database if it doesn't exist db.row_factory = sqlite3.Row db.execute('drop table if exists test') db.execute('create table test(t1 text, i1 int)') db.execute('insert into test (t1, i1) values(?,?)', ('one', 1)) you can directly substitute the values in ?,? but variable names allow for code re-usability db.execute('insert into test (t1, i1) values(?,?)', ('two', 2)) db.execute('insert into test (t1, i1) values(?,?)', ('three', 3)) db.commit() # without a commit no changes to the database will be recorded cursor = db.execute('select * from test order by i1') for row in cursor: print row['i1'], row['t1'] # Each record is fully indexed by the field heading due to Row Factorymain()Spot checkCreate a database using sqlite3Each row in the database contains the following information (Make about 5 entries)ID (alphanumeric)Last name (alpha)First name (alpha)Hire year (int)Enter data in random order, then display all in order of hire yearEvent driven programmingThis is another way to think about flow control in a program.An important consideration is parallelism (or pseudo-parallelism)If there is only one processor, and we write the program to support more than one event at once, then the one processor gives slices of time to each event.All modern computers have multi core architecture more than one processor available. It is possible to have more than one event process happening at the same time.So farMost of our programs are basically sequential, with excursions into functions and classes for special purposesThere is a clearly defined sequence of actions that the program will perform.

Event Driven ProgramsIn event-driven programs, the sequence of actions is not known in advanceThe program has the facility to respond to external events and take appropriate action.Now, programming means determining what events might happenrecognizing each eventtaking appropriate action for the eventwaiting for the nextsometimes accommodating simultaneous eventsError eventsAn event may be a special case of normal programs such as an error eventWe have seen how to handle errorsThis is a form of interrupt handlingnumber = 0while not 1 ', param, 'has joined the chat room' elif command == 'LEFT': print '==>', param, 'has left the chat room' elif command == 'MESSAGE': i += 1 # need next line for content print '==>', param + ': ' + lines[i] elif command == 'PRIVATE': i += 1 # need next line for content print '==>', param + ' [private]: ' + lines[i] i += 1instructions = """--------------------------------------------Welcome to the chat room.

To quit, use syntax, quit

To send private message to 'Joe' use syntax, private Joe:how are you?

To send message to everyone, use syntax, hi everyone!--------------------------------------------"""

server = socket() # shared by both threadsserver.connect( ('localhost', 9000) ) # could be a remote hostusername = raw_input('What is your name: ').strip()server.send('ADD %s\n' % username )incoming = IncomingThread()incoming.start()print instructionsactive = True # main thread for user inputwhile active: message = raw_input() # wait for more user input if message.strip(): if message.rstrip().lower() == 'quit': server.send('QUIT\n') active = False elif message.split()[0].lower() == 'private': colon = message.index(':') friend = message[7:colon].strip() server.send('PRIVATE %s\n%s\n' \ % (friend,message[1+colon: ]) ) else: server.send('MESSAGE ' + message)