Interfacing With Mysql Our Database of Python Scripts Widgets in The Gui

Download as ps, pdf, or txt
Download as ps, pdf, or txt
You are on page 1of 6

MCS 275 L-23 MCS 275 L-23 MCS 275 L-23

Interfacing with MySQL our Database of Python Scripts Widgets in the GUI
7 March 2008 7 March 2008 7 March 2008
viewing it with a GUI
A GUI to browse a MySQL table A GUI to browse a
MySQL table
A GUI to browse a
MySQL table
A GUI to browse a
MySQL table
our database with Python scripts our database with Python
scripts We create one table scripts in the database
our database with Python
scripts
our database with Python
scripts

connecting to database, setting sort order connecting to database,


setting sort order
OurPyFiles, storing data about our Python scripts.
connecting to database,
setting sort order Message field to write status information. connecting to database,
setting sort order
retrieving and displaying retrieving and displaying retrieving and displaying
retrieving and displaying records
Buttons to 
records records records

Normalization For every Python script we have 4 fields: Normalization Normalization



Normalization splitting a table in two
moving data into the tables its type, number, date, and file name. splitting a table in two
moving data into the tables
connect to the database splitting a table in two
moving data into the tables

splitting a table in two Example of a header: 


Retrieving Specific
Records
Retrieving Specific
Records
retrieve all records Retrieving Specific
Records
moving data into the tables 
use the key to access a
record
# L-23 MCS 275 Fri 7 Mar 2008 : guidb1.py
use the key to access a
record see next 10 or previous 10 records use the key to access a
record
inserting a new record in a inserting a new record in a inserting a new record in a
table table table
Retrieving Specific Records Radio buttons to determine
use the key to access a record Corresponding data tuple:

which field to use for sorting
inserting a new record in a table (’L’, ’23’, ’2008-03-07’, ’guidb1.py’) 
sort in ascending or descending order

MCS 275 Lecture 23 With a GUI we get a better overview.


Programming Tools and File Management We will sort the records in various ways.
Jan Verschelde, 7 March 2008

MCS 275 L-23 MCS 275 L-23 MCS 275 L-23


Viewing the Table scripts Message Label and other labels Connecting to the Database
7 March 2008 7 March 2008 7 March 2008

A GUI to browse a Code in __init__: A GUI to browse a Button defined in __init__: A GUI to browse a
MySQL table MySQL table MySQL table
our database with Python our database with Python our database with Python
scripts scripts scripts
connecting to database, self.message = StringVar() connecting to database, self.bc = Button(wdw, text=’connect’, \ connecting to database,
setting sort order setting sort order setting sort order
retrieving and displaying self.message.set("welcome to our database") retrieving and displaying command = self.connect) retrieving and displaying
records records records
self.messageLabel = Label(wdw, \ self.bc.grid(row=1,column=0)
Normalization Normalization Normalization
splitting a table in two
textvariable = self.message) splitting a table in two
self.cursor = 0 splitting a table in two
moving data into the tables
self.messageLabel.grid(row=0,column=0,columnspan=4) moving data into the tables moving data into the tables

Retrieving Specific Retrieving Specific Retrieving Specific


Records Records
def connect(self): Records
use the key to access a
record
self.tt = Label(wdw, text=’type’) use the key to access a
record
""" use the key to access a
record
inserting a new record in a
table
self.tt.grid(row=2,column=0) inserting a new record in a
table
Connects to the database OurPyFiles. inserting a new record in a
table
self.dd = Label(wdw, text=’date’) """
self.dd.grid(row=2,column=1) try:
self.ff = Label(wdw, text=’file’) db = MySQLdb.connect(db="OurPyFiles")
self.ff.grid(row=2,column=2,columnspan=2) self.message.set("connected to \"OurPyFiles\"")
self.cursor = db.cursor()
self.sL = Label(wdw, text=’sort by’) except:
self.sL.grid(row=4,column=0) self.message.set("failed to connect to \"OurPyFiles\"")
MCS 275 L-23 MCS 275 L-23 MCS 275 L-23
Radio Button to sort Radio Button to order Formulating the Query
7 March 2008 7 March 2008 7 March 2008

We can sort on type, date, or file. A GUI to browse a A GUI to browse a def query(self): A GUI to browse a
MySQL table MySQL table MySQL table
"""
Code for RadioButton in __init__:
our database with Python
scripts User has choice between ascending or descending order. our database with Python
scripts
our database with Python
scripts
connecting to database, connecting to database, Returns the query to select all records, connecting to database,
setting sort order setting sort order setting sort order
retrieving and displaying Code for RadioButton in __init__: retrieving and displaying taking input from the radio buttons. retrieving and displaying
records records records
self.RadioSort = IntVar() """
Normalization Normalization Normalization
self.st = Radiobutton(wdw, text=’type’, \ splitting a table in two self.RadioOrder = IntVar() splitting a table in two q = ’select * from scripts’ splitting a table in two
moving data into the tables moving data into the tables moving data into the tables
variable = self.RadioSort, value = 1) self.asc = Radiobutton(wdw, text=’ascending order’, \ ord = ’’
Retrieving Specific Retrieving Specific Retrieving Specific
self.st.grid(row=4,column=1) Records variable = self.RadioOrder, value = 1) Records if self.RadioOrder.get() == 1: Records
self.sd = Radiobutton(wdw, text=’date’, \ use the key to access a
record self.asc.grid(row=5,column=0,columnspan=2) use the key to access a
record
ord = ’asc’ use the key to access a
record

variable = self.RadioSort, value = 2) inserting a new record in a


table self.dsc = Radiobutton(wdw, text=’descending order’, \
inserting a new record in a
table
elif self.RadioOrder.get() == 2: inserting a new record in a
table

self.sd.grid(row=4,column=2) variable = self.RadioOrder, value = 2) ord = ’desc’


self.sf = Radiobutton(wdw, text=’file’, \ self.dsc.grid(row=5,column=2,columnspan=2) if self.RadioSort.get() == 1:
variable = self.RadioSort, value = 3) self.RadioOrder.set(1) q = q + ’ order by t, n ’ + ord
self.sf.grid(row=4,column=3) elif self.RadioSort.get() == 2:
self.RadioSort.set(1) The default order is set to ascending. q = q + ’ order by d ’ + ord
elif self.RadioSort.get() == 2:
The default sort is set to type. q = q + ’ order by f ’ + ord
return q

MCS 275 L-23 MCS 275 L-23 MCS 275 L-23


Retrieving Records Displaying Data in Listboxes Using listboxes
7 March 2008 7 March 2008 7 March 2008
second button
A GUI to browse a A GUI to browse a A GUI to browse a
def retrieve(self): MySQL table MySQL table MySQL table
our database with Python our database with Python
def clear(self): our database with Python
""" scripts To display the data, we use Listbox widgets. scripts
""" scripts
connecting to database, connecting to database, connecting to database,
Retrieves all records from the scripts table. setting sort order setting sort order
Clears all listboxes. setting sort order
retrieving and displaying We will use three listboxes (defined in __init__): retrieving and displaying retrieving and displaying
""" records records
""" records

if self.cursor == 0: Normalization 1. for type and number, e.g.: L-23 Normalization Normalization
splitting a table in two splitting a table in two
self.Lt.delete(0,END) splitting a table in two
self.message.set("please connect first") moving data into the tables self.Lt = Listbox(wdw,width=4,height=10) moving data into the tables
self.Ld.delete(0,END) moving data into the tables

else: Retrieving Specific self.Lt.grid(row=3,column=0) Retrieving Specific self.Ln.delete(0,END) Retrieving Specific


Records Records Records
q = self.query() use the key to access a 2. for the date, e.g.: 2008-03-23 use the key to access a use the key to access a
record record record
lc = self.cursor.execute(q) inserting a new record in a inserting a new record in a def insert(self,item): inserting a new record in a
table self.Ld = Listbox(wdw,width=10,height=10) table table
m = ’retrieved %d records’ % int(lc) """
self.Ld.grid(row=3,column=1)
self.message.set(m) Inserts one record item to the listboxes.
R = self.cursor.fetchall() 3. for the file name, e.g.: guidb1.py """
self.clear() t = item[0] + ’-’ + str(int(item[1]))
self.Ln = Listbox(wdw,width=15,height=10)
for i in range(0,len(R)): self.Lt.insert(END,t)
self.Ln.grid(row=3,column=2,columnspan=2)
if i >= 10: break self.Ld.insert(END,str(item[2]))
self.insert(R[i]) self.Ln.insert(END,item[3])
self.records = R
self.pos = 10
MCS 275 L-23 MCS 275 L-23 MCS 275 L-23
Buttons to Navigate Displaying next 10 Records Displaying previous 10 Records
7 March 2008 7 March 2008 7 March 2008

Because our listboxes are only 10 in height, A GUI to browse a A GUI to browse a A GUI to browse a
MySQL table MySQL table MySQL table
we cannot display everything all at once. our database with Python our database with Python our database with Python
scripts def next10(self): scripts def prev10(self): scripts

Two navigation buttons in __init__: connecting to database,


setting sort order """
connecting to database,
setting sort order """
connecting to database,
setting sort order
retrieving and displaying retrieving and displaying retrieving and displaying
records Displays the next 10 records in listboxes. records Displays the previous 10 records in listboxes. records
1. to show the next 10 records: Normalization """ Normalization """ Normalization
splitting a table in two splitting a table in two splitting a table in two
self.bn = Button(wdw, text=’next 10’, \ moving data into the tables if self.records == 0: moving data into the tables if self.records == 0: moving data into the tables

command = self.next10) Retrieving Specific self.message.set("no records to show") Retrieving Specific self.message.set("no records to show") Retrieving Specific
Records Records Records
self.bn.grid(row=1,column=2) use the key to access a
else: use the key to access a
else: use the key to access a
record record record
self.clear() self.clear()
2. to show the previous 10 records: inserting a new record in a
table
inserting a new record in a
table
inserting a new record in a
table
for i in range(self.pos,self.pos+10): self.pos = self.pos - 20
self.bp = Button(wdw, text=’previous 10’, \ if i >= len(self.records): break if self.pos < 0: self.pos = 0
command = self.prev10) self.insert(self.records[i]) for i in range(self.pos,self.pos+10):
self.bp.grid(row=1,column=3) self.pos = self.pos + 10 if i >= len(self.records): break
if self.pos >= len(self.records): self.insert(self.records[i])
Storing the current position in the retrieved records: self.pos = len(self.records) - 1 self.pos = self.pos + 10
self.pos = 0

MCS 275 L-23 MCS 275 L-23 MCS 275 L-23


Making the Database more useful The Function main() Creating the Tables
7 March 2008 7 March 2008 7 March 2008
splitting the table scripts
A GUI to browse a A GUI to browse a A GUI to browse a
MySQL table MySQL table MySQL table
our database with Python
def main(): our database with Python our database with Python
scripts scripts scripts
connecting to database, """ connecting to database, connecting to database,
The four fields were copied from the headers. setting sort order setting sort order setting sort order
retrieving and displaying Splits scripts in two tables. retrieving and displaying retrieving and displaying

Two drawbacks:
records records
def CreateTables(c): records

Normalization """ Normalization Normalization


splitting a table in two splitting a table in two
""" splitting a table in two
1. only the file name is unique for every record moving data into the tables
db = MySQLdb.connect(db="OurPyFiles") moving data into the tables
Executes the MySQL commands to create moving data into the tables

and not so convenient to use as key Retrieving Specific c = db.cursor() Retrieving Specific
the tables typedate and filedata.
Retrieving Specific
Records Records Records
2. as most lectures featured more than one script, use the key to access a q = ’select * from scripts order by d’ use the key to access a use the key to access a
record record The input parameter c is the cursor. record

there is a lot of redundant data in the table inserting a new record in a lc = c.execute(q) inserting a new record in a inserting a new record in a
table table """ table

print ’found %d records’ % int(lc)


We normalize, using scripts to create two new tables: CreateTypeDate(c)
A = c.fetchall()
one with file names and one with type and dates. CreateFileData(c)
CreateTables(c)
Because tedious to do manually with the mysql monitor, (T,F) = SplitRecords(A)
we develop a script. InsertTypeDate(c,T)
InsertFileData(c,F)
MCS 275 L-23 MCS 275 L-23 MCS 275 L-23
Create Table typedate Create Table filedata Splitting Records
7 March 2008 7 March 2008 7 March 2008

A GUI to browse a A GUI to browse a def SplitRecords(R): A GUI to browse a


MySQL table MySQL table MySQL table
def CreateTypeDate(c): our database with Python def CreateFileData(c): our database with Python """ our database with Python
scripts scripts scripts
""" connecting to database, """ connecting to database, Returns two lists: records that go connecting to database,
setting sort order setting sort order setting sort order

The table typedate stores type and date, retrieving and displaying The table filedata stores file names, retrieving and displaying in typedate and in filedata. retrieving and displaying
records records records

e.g.: L-4 and 2008-01-23, repesented by represented by three fields: id, name, """
Normalization Normalization Normalization
splitting a table in two splitting a table in two L = []; T = []; F = []; cnt = -1 splitting a table in two
four fields: id, type, number, and date. moving data into the tables
and id of the corresponding entry in moving data into the tables moving data into the tables
for i in range(0,len(R)):
The input parameter c is the cursor. Retrieving Specific the typedate table. c is the cursor. Retrieving Specific
d = R[i] Retrieving Specific
Records Records Records
""" use the key to access a """ use the key to access a
p = (d[0],d[1],d[2]) use the key to access a
record record record

try: inserting a new record in a


table
try: inserting a new record in a
table if p in L: inserting a new record in a
table

td = ’create table typedate ’ + \ fd = ’create table filedata ’ + \ ind = L.index(p)


’( i INT, t CHAR(1), n INT, d DATE )’ ’( i INT, f CHAR(20), t INT )’ else:
c.execute(td) c.execute(fd) cnt = cnt + 1
L.append((d[0],d[1],d[2]))
print td + ’ succeeded’ print fd + ’ succeeded’
T.append((cnt,d[0],d[1],d[2]))
except: except: ind = cnt
print td + ’ went wrong...’ print fd + ’ went wrong...’ F.append((i,d[3],ind))
return (T,F)

MCS 275 L-23 MCS 275 L-23 MCS 275 L-23


Inserting Type and Date Inserting File Names A Sanity Check
7 March 2008 7 March 2008 7 March 2008

A GUI to browse a A GUI to browse a A GUI to browse a


MySQL table MySQL table MySQL table
our database with Python our database with Python our database with Python
scripts scripts scripts
def InsertTypeDate(c,T): connecting to database,
def InsertFileData(c,F): connecting to database,
def DateFiles(c): connecting to database,
setting sort order setting sort order setting sort order
""" retrieving and displaying
records """ retrieving and displaying
records
""" retrieving and displaying
records

Given the cursor and a list of values for Normalization Given the cursor and a list of values for Normalization As a final check, selects file name Normalization
the table typedate, all records are added. splitting a table in two
moving data into the tables the table filedata, all records are added.
splitting a table in two
moving data into the tables
and corresonding date from the newly splitting a table in two
moving data into the tables

""" Retrieving Specific """ Retrieving Specific created tables. c is the cursor. Retrieving Specific
Records Records Records
for i in range(0,len(T)): """
use the key to access a
record for i in range(0,len(F)): use the key to access a
record
use the key to access a
record
p = T[i] inserting a new record in a
n = F[i] inserting a new record in a q = ’select f,d from filedata, typedate’ \ inserting a new record in a
table table table

q = ’insert into typedate values ’ + \ q = ’insert into filedata values ’ + \ + ’ where filedata.t = typedate.i’
’(\"%s\", \"%s\", \"%s\", \"%s\") ’ \ ’(\"%s\", \"%s\", \"%s\") ’ \ c.execute(q)
% (str(p[0]), str(p[1]), str(p[2]), \ % (str(n[0]), n[1], str(n[2])) R = c.fetchall()
str(p[3])) c.execute(q) print R
c.execute(q) print ’#records :’, len(R)
MCS 275 L-23 MCS 275 L-23 MCS 275 L-23
Using Keys The Widgets in the GUI Query for Specific Record
7 March 2008 7 March 2008 7 March 2008

A GUI to browse a A GUI to browse a A GUI to browse a


MySQL table MySQL table MySQL table
our database with Python our database with Python our database with Python
scripts scripts scripts
connecting to database, connecting to database, connecting to database,
setting sort order setting sort order setting sort order
retrieving and displaying
records
retrieving and displaying
records
def query(self,key): retrieving and displaying
records

After the normalization, every script has a unique key. Normalization Normalization
""" Normalization

This key is in the i field of the table filedata. splitting a table in two splitting a table in two Returns the query for all the information splitting a table in two
moving data into the tables moving data into the tables moving data into the tables
of the script with the given key.
Retrieving Specific Retrieving Specific Retrieving Specific
Accessing the data via the key allows us to Records Records """ Records
use the key to access a use the key to access a use the key to access a

1. select records directly record record q = ’select typedate.t, n, d, f ’ + \ record


inserting a new record in a inserting a new record in a inserting a new record in a
table table ’from typedate, filedata ’ + \ table
2. insert, delete, and update records. ’where filedata.t = typedate.i ’ + \
’and filedata.i = %d’ % key
return q

MCS 275 L-23 MCS 275 L-23 MCS 275 L-23


Counting the Number of Files Inserting a new File Inserting a new File
7 March 2008 7 March 2008 7 March 2008

A GUI to browse a A GUI to browse a A GUI to browse a


MySQL table MySQL table MySQL table
our database with Python our database with Python our database with Python
scripts scripts scripts
connecting to database, connecting to database, connecting to database,
setting sort order
retrieving and displaying Entering the data: setting sort order
retrieving and displaying
setting sort order
retrieving and displaying

def CountFiles(self):
records records
Asking to confirm the data: records

Normalization Normalization Normalization


""" splitting a table in two splitting a table in two splitting a table in two
moving data into the tables moving data into the tables moving data into the tables
Returns the number of files.
Retrieving Specific Retrieving Specific Retrieving Specific
""" Records Records Records
q = ’select count(*) from filedata’ use the key to access a
record
use the key to access a
record
use the key to access a
record

r = self.cursor.execute(q) inserting a new record in a


table
inserting a new record in a
table
inserting a new record in a
table

n = self.cursor.fetchone()
return int(n[0])
MCS 275 L-23 MCS 275 L-23 MCS 275 L-23
Inserting a new File Inserting Data Inserting a Record
7 March 2008 7 March 2008 7 March 2008

A GUI to browse a A GUI to browse a A GUI to browse a


MySQL table def InsertData(self): MySQL table MySQL table
our database with Python
scripts """ our database with Python
scripts
def InsertRecord(self,data): our database with Python
scripts
connecting to database,
setting sort order Inserts a new record into the database. connecting to database,
setting sort order
""" connecting to database,
setting sort order

Confirming the insert: retrieving and displaying


records """ retrieving and displaying
records
Prepares data to insert a record. retrieving and displaying
records

Normalization t = self.tp.get() Normalization """ Normalization


splitting a table in two
moving data into the tables
d = self.dt.get() splitting a table in two
moving data into the tables
L = data[0].split(’-’) splitting a table in two
moving data into the tables

Retrieving Specific
f = self.nm.get() Retrieving Specific
t = L[0]; n = L[1] Retrieving Specific
Records r = (t,d,f) Records d = data[1]; f = data[2] Records
use the key to access a use the key to access a use the key to access a
record
if not self.startinsert: record nf = self.CountFiles() record
inserting a new record in a inserting a new record in a inserting a new record in a
table
m = ’inserting %s,’ % str(r) table nt = self.CountTypes() table

m = m + ’press to confirm’ v = ’(’ + ’\"’ + str(nf) + ’\"’ + \


self.message.set(m) ’,’ + ’\"’ + f + ’\"’ + ’,’ + \
self.startinsert = True ’\"’ + str(nt) + ’\"’ + ’)’
else: self.InsertFileValues(v)
self.InsertRecord(r) m = ’inserted %s’ % v
m = ’inserted %s’ % str(r) self.message.set(m)
self.startinsert = False

MCS 275 L-23 MCS 275 L-23


Inserting Values Summary and Assignments
7 March 2008 7 March 2008

A GUI to browse a A GUI to browse a


MySQL table MySQL table
our database with Python our database with Python

Recall the MySQL command: scripts


connecting to database, See Making Use of Python for web interfaces.
scripts
connecting to database,
setting sort order setting sort order
retrieving and displaying retrieving and displaying
records records
insert into <table> values <tuple> Normalization
Exercises: Normalization
splitting a table in two splitting a table in two

def InsertFileValues(self,v):
moving data into the tables 1. Create the equivalent to guidb1.py, our first GUI, moving data into the tables

"""
Retrieving Specific
Records
writing a CGI script. Retrieving Specific
Records

Inserts values in filedata table.


use the key to access a
record 2. The method in our second GUI to insert is not yet use the key to access a
record
inserting a new record in a inserting a new record in a

""" table complete. Also provide functions to add the table

q = ’insert into filedata values ’ corresponding values in the table typedate.


q = q + v 3. Provide functions to delete records.
self.cursor.execute(q) 4. Provide functions to update records.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy