




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
AND
Welldone!
You’vemadeitthroughtheforestofTkinter,pastthehauntedlakeofPmwandemerged(fairly)unscathedfromaduelwithTabnanny.Goodonya!
Now,itgetsREALLYinteresting
Obviously,you’veallreadthestudydesignforUnit4andyouwouldknowthattheSACforOutcome1isasfollows:
“Oncompletionofthisunitthestudentshouldbeabletoapplythestagesofsoftwaredevelopmenttoproducepurpose-designedsoftwarethattakesintoaccountanetworkedinformationsystemobjectiveandtheneedsofend-users.”
AfewkeywordsherethatIhavehighlightedforyou:
Firstly–Youhavetodesignyourownsoftware(justlikeinUnit3)usingPythontomeetanobjective
Secondly–Weneedtouseanetworkedinformationsystem–sothatanumberofpeoplecanusethesystemsimultaneously.RememberyourSACinUnit3?Well,reallyonlyoneuseratatimecoulduseit–NOGOODforanetworkedsystem
Thirdly–weneedtomeettheneedsoftheusersofaparticularscenario
So,whatwe’regoingtodoiscreateaGUI(GraphicalUserInterface)usingTkinter,toallowustoenterandretrievedatathatissavedinaMySQLdatabase.
I’mnotgoingtogointoagreatdealaboutwhatMySQLis,howitworksetc.,shortofsayingthatitsFREE,youcandownloaditathomeifyouwant,it’sadatabaseanditsprettycommonthroughouttheworld.Therearelotsofvariationsonit(PostGreSQL,MSSQLamongstothers)
Ifyouwantmoreinformation–goto
andthere’sloadsofinformation
Onwiththeshow…
Chapter1–GettingMySQLinstalledandsorted
Thankfully,MySQLisalreadyinstalledandreadytogoonour(your)serverthatyouaregoingtobeplayingwith,sononeedtoworryaboutthat.Ifyouwanttosetitupathome,goto
,downloadtheversionthatyouneedandfollowtheinstructions–deadeasy.IfyouDONOThaveaccesstotheinternet,oryouareondialup,seemeforacopyofMySQLthatyoucanhaveonyourflashdrive.
YouwillalsoneedtodownloadtheMySQLbindingsthatallowPythontotalktoMySQL–thesearealreadydownloadedforus,sononeedtoworry,butifyouwanttoinstalltheseathome,goto:
/project/showfiles.php?group_id=22307
anddownloadthelatestreleaseversion(attimeofwritingitwas1.2.2)orseemewithyourflashdrive.Youjustrunthe.exefile–deadeasy!
Ok,sotogetaccesstoMySQLontheserver,youneedtotypein
Athome,youneedtogotoSTART>PROGRAMS>MySQL>MySQLServer5.0>MySQLCommandLineClientandinputdetailsstraightfromthere.
Chapter2–SomeSQLqueries
Youshouldnowbefacedwithablackwindow(calledtheCOMMANDLINECLIENT)whereyouinputdata.Itwilllooksomethinglikethis.
YourPASSWORDisxxxxxx
Nowthescreenwilllooklikethis
Allyourcommandstocreateyourdatabasetableandsetfieldsizes,namesandthesuchlikewillbedonehere
Typehelpafterthemysql>cursor
Youwillhavealistofcommandsthatyoucanuse.AtthelevelweareusingMySQL,wewon’tbeusingmanyofthese,withtheexceptionofUSEandEXIT.
NOTICEhowthemysql>cursorisback–thatmeansyoucantypesomethinginstraightaway.
NowtypeinSELECTVERSION(),CURRENT_DATE;
YoushouldhaveatabletellingyoutheversionofMySQLthatyouareusingandthecurrentdate
MySQLisnottoobotheredaboutcase,soyoucouldtypein:
selectversion(),current_date;
Nowtry:
SELECTUSER();
Theresultofthisisgoingtobeimportant,somakeanoteofit.WhenItypethisinIgetthisresult:
NOTICEthatItypedinselectuser()andpressedEnter,thentypedin;togettheresult.AllqueriesinMySQLneedtoendwithasemicolon(;).Ifyoudon’tputitin,thennothingwillhappenandyouwillneedtoenteritatthenextcursor.
NOTICEthattheresultofthisisroot@localhost
rootismyUSER
localhostismyhost.
Iwillneedtousetheseinmyscriptlateron,sokeepanoteoftheresultyouget.
Chapter3–Creatingadatabase
Let’ssaywewanttocreateadatabaseofourpetsandtheirdetails.
Firstthingwedoisseewhatdatabasesalreadyexistonourserver,sothatwewon’ttakeanamethatalreadyexists.
TypeSHOWDATABASES;
Youshouldgetthis(above),WITHOUTtheonecalledhours(that’smytestdatabase)
Clearly,youwillnotcallyourdatabaseinformation_schema,mysqlortest.
AlsoNOTICEthatadatabaseshouldbeONEWORDorjoinedbyanunderscore(orsimilar)
LetscallourdatabasePETSRT(wherethenameisPETSwithmyinitialsafterwards)butUSEYOUROWNINITIALS!
TypeinCREATEDATABASEPETSRT;
ThentypeUSEPETSRT;
NowweneedtocreateaTABLEinthatdatabase.Reallyadvanceddatabasescanhavemorethanonetable(askanyonedoingITApps!),butwe’llstickwithonetablefortoday.
TypeinCREATETABLEpets(nameCHAR(200),ageINT(5),sexCHAR(1),speciesCHAR(100),breedCHAR(30);
ThiswillCREATEatablecalledpets.Therewillbe5fields,eachofvaryinglengths(chosendependingonwhatisgoinginthefields)
TheotherchoicesofDATASTRUCTUREarebelow
Don’taskmewhattheyallmean,butthecommononesareCHAR,INT,DATETIME,FLOAT,DATE,TIMESTAMPandYEAR,andthat’smorethanenoughtobegoingonwith!
NowtypeinEXPLAINpets;
ThiswillbringupasummaryofyourtableandthetypeofDATASTRUCTURESthatyouhave:
ThescreenshotaboveiswhenIgottheresultformytestdatabasecalledhours.
NOTICEthatyoutypeinEXPLAIN<tablename>NOTEXPLAIN<databasename>.Acommonerror…
Nowyouneedtoensurethatyouhaveaccesstoread/writetoyourSQLdatabase,BEFOREwestartcoding.
GRANTALLON*.*TOROOT@LOCALHOSTIDENTIFIEDBY“PASSWORD”;
Someexplanation:
WeneedtoGRANTaccesstotheusernameandhostnamethatwefoundoutearlier,soreplaceROOT@LOCALHOSTwithwhateveryougotfromCHAPTER2.
ReplacePASSWORDwithapasswordthatyouwanttouse.This‘stops’othersfromaccessingyourtable(unlesstheyseeyourcode)
NowtypeSELECT*FROMPETS
Itwill(hopefully)reportbackthatyouhavean‘EmptySet’whichmeansthatthereareNORECORDSinthattable.Whichtherearen’t.‘Coswehaven’tputanyinyet.
REMEMBERthatadatabaseissplitintoTABLES.WeneedtoUSEdatabase_nameandthenoperateontable_name
InsertingData
WewillbeinsertingdataviaourPythonscript,butifyouwanttoseethatyourdatabaseworks…
TypeinINSERTINTOpetsVALUES(‘Puffball’,‘12’,‘F’,‘Dog’,‘Rottweiller’);
Thiswillinsertthesevaluesintheorderofthefields(NamethenAgethenSexthenSpeciesthenBreed).Ifyouwantafieldblank,thentypeNULL.
NowtypeinSELECT*FROMpets
Andyourfirstpetshouldbeinthere!
IfyouhadLOTSofdatatoinsertfromExcelforexample,youcansaveitasa.csvfile(commaseparatedvalues)andloaditasabatch,ratherthantypingtheminsingly)
ThisbringsupapointofPLANNINGYOURDATABASE.
YouMUST,MUST,MUSTmakesurethatyourdatabasehasthecorrectfields,fieldlength,datastructureandorderoffieldsBEFOREyoustarttypingitintoMySQL.
Planitonpaperfirst,askotherpeoplewhattheythinkandTHINKABOUTYOURFINALSOLUTION–whoaretheusersandwhatdotheywant?
Youcanalteryourfieldsifyoumakeamistake(clickhere),butit’saLOTlesshassletogetitrightstraightaway
Chapter4–SortingourGUIout
Right,nowthatthebonesofourdatabaseissorted,weneedtocreateaprogramtouseourSQLdatabase
Createatkinterprogramthatisstructuredlikethis.Includeabuttonthatsavesthedata(don’tcreatethedeffunction,justwritepassinthecode).Yourdeletebuttonshoulddeletethecontentsofalltheentryboxes.Yourquitbuttonshoulddestroytherootwindow.
Deadeasy!–whaddyareckon–10minutes?
YoucanputthebuttoninthatsaysIGNOREME,justdon’tcreateadefforit(usepass)
Don’tpanicifyoucantrememberhowtodothisstuff–youhaven’treallydonethebasicssinceU3O2.
Usethetutorialsandyourpreviousprogramstohelpyou!
LayoutyourGUIhowyouwant–remembertomakeitattractive,colourfulandwellplanned.
Use.grid,buttonpicturesanddifferentfonts.
Beginyourscriptwiththis:
importMySQLdb
forfairlyobviousreasonsandthencontinueasnormal.
Chapter4–ConnectingourGUItoMySQL
Thisisthetrick,anditsNOTevendifficult!
ThisisthedeffunctionformySAVEbutton.
defbut1():
name=E1.get()
hours=E2.get()
rate=E3.get()
wage=E4.get()#'Gets'thedatafromEntryboxesE1,E2,E3,E4
myquery="INSERTINTOhours_worked(name,hours,rate,wage)VALUES(\'"+name+"\',\'"+hours+"\',\'"+rate+"\',\'"+wage+"\')"
db=MySQLdb.connect(host='localhost',user='root',passwd='hamish',db='hours')#Creates'myquery'andinsertstheresultsofthisintoapre-createdMySQLtable
curs=db.cursor()#Createsacursortomakechangesinthetable
curs.execute(myquery)#Thisexecutesthe'myquery'
curs.close()
mit()#thisistheCRUCIALlinethatneedstobeheretoCOMMITthechangestothedatabase
db.close()#thisclosesthedatabasetoanymorechanges
Thebitshighlightedinbluearetheonesyouneedtobeawareof.Thebitshighlightedinyellowaremyinternalcomments
Theotherbitsarefairlyobvious.
myqueryisthenamewe’regoingtogiveforthequery(eachqueryneedsadifferentname)
INSERTINTOhours_workedVALUESisanSQLcommand–INSERTINTOtellsPythontoINSERTthedataINTOatable(inmycasecalledhours_worked,inyourcaseitwouldbe…
(\'"+name+"\',\'"+hours+"\',\'"+rate+"\',\'"+wage+"\')"–ThesearethenamesofthefieldsinyourSQLdatabase.TheyneedtobeTHESAME.Exactly.Soyourswouldbename,age,sexetc.Pythongetsthevaluesforname,ageetc.fromthebitatthetopofthedeffunction(name=E1.get()etc.).ReplaceE1.get()withthenameofyourEntryboxesandreplacename,hoursetc.withthenamesofyourfields.
db=MySQLdb.connect(host='localhost',user='root',passwd='hamish',db='hours')–thisisprettyobviousstuff–replacewithyourdetails
TherestofthecodeinblueisexplainedintheINTERNALCOMMENTS.
Eachlineiscrucial–makesureyouhavethemallandinthatorder.
Theonlybityoucanalteristhe
curs.execute(myquery),whereyouwouldchangemyquerytosomethingelse,ifyouchangeditfurtherupinthecode
Whew!
Chapter4–Checkingitsallthere
Right,ourGUIissendingdatatotheSQLtableinourdatabase.Butweneedtocheckitsthere,bothinSQLformandalsothroughourGUI–rememberthatwedon’twantourclienthavingtogothroughtheSQLcommandlineinterfaceallthetime.Firstthingsfirst…
GototheMySQLcommandlineinterface,aswedidinChapter2
Typeinyourpassword
TypeSHOWdatabases;
TypeUSE<your_database_name>;
TypeSELECT*FROM<your_table_name>;
Hopefully(really,reallyhopefully),youshouldhavearecordinyourtablethattellsusallaboutPuffballtherottweiller!
IwouldadviseyoutocheckyourSQLtableatregulartimes,justtomakesurethatallisok–keepthecommandlineinterfaceopenwhenyou’retkinter-ing,andcheckwhenrequired.
Ok,sothat’showwecheckthroughSQL,butwhataboutcheckingthecontentsthroughourGUI…
We’regoingtousealistboxtoupdatetherecordsfromtheSQLtabletoourGUI,herewego…
STEP1–InsertaLISTBOX
Youshouldrememberhowtodothis,ifnot…
b5=Button(root,text="AddtoListBox",command=but5)
b5.pack()
list=Listbox(root)
list.pack(expand=1,fill=BOTH)
Insertthisunderallyourbuttonsandentryboxes
STEP2–Createacursorforthistask
defget_cursor_for_pets_table():
db=MySQLdb.connect(host='localhost',user='root',passwd='hamish',db='pets')
curs=db.cursor()
returncurs
Putthisinyourdefssomewhere.Remembertochangehost,user,passwordanddbnametoYOURdetails!
STEP3–CollectallthedatafromthetableinthedatabasebyusingtheFETCHALLcommand,closethecursordownand‘return’ourResults
defget_all_entries():
curs=get_cursor_for_pets_table()#Thepreviousdefinition
myquery="SELECT*FROMpets"#Thenameofourquery
curs.execute(myquery)#Executesthe‘myquery’
Results=curs.fetchall()#Fetchesallthedata
curs.close()
returnResults#Returnstheresults
Putthisunderyourpreviousdefinition
STEP4–PutallthisdataintoourLISTBOX
defbut5():
results=get_all_entries()#‘results’isthepreviousdef
list.delete(0,END)
forresultinresults:
printresult
name=result[0]
age=result[1]
sex=result[2]
species=result[3]
breed=result[4]
list.insert(END,name+""+age+""+sex+""+species+““+breed)#printallresultsinthelistbox
The““justputspacesinbetweenthevariables–ifyouwantedto,youcouldincludewritinghere,suchas“Name=”or“Sex=”etc.tomakeyourlistboxabitclearer.
STEP5–InitiatetheListbox…
list=Listbox()
list.pack(expand=1,fill=BOTH)
root.mainloop()
Done!
Chapter5–SomefunkyGUI/MySQLstuff
Timestamps
WhatifyouwantedtoknowWHENarecordwaslastinserted?Youcouldeitherasktheusertoinsertthedate(andgivethefieldaDATETIMEdatastructure)whichwouldinvolvealotoftypingfromtheuserORgetSQLtoautomaticallyrecordthedate&time.IknowwhichI’dratherdo…
Thisiseasy…
WhenyoucreateyourtableinMySQL,justcreateafieldcalleddate/date_enteredorsomethinglikethatandgiveitthedatastructuretitleTIMESTAMP,likebelow…
createtablehours_worked(nameCHAR(255),hoursCHAR(255),rateCHAR(255),date_enteredTIMESTAMP)
Eachtimearecordiscreated,itautomaticallyinsertsatime/datestamp–handy…
Deletingarecord
Tobeadded
Addingascrollbar
WhatifyouhavesomanyentriesinyourListboxthatyoucantseethemall?Youneedtogetyourselfascrollbar!
ThiscodegoesintothebitthatinitiatedourListbox(seeChapter4)
scrollbar=Scrollbar()
scrollbar.pack(side=RIGHT,fill=Y)
list=Listbox(root,yscrollcommand=scrollbar.set)
list.pack(expand=1,fill=BOTH)
scrollbar.config(command=list.yview)
The‘yview’isascrollbarthatgoesvertically.Youcanalsohave‘xview’whichisascrollbarthatgoeshorizontally–youprobablywontneedthis…
Chapter6–Alteringyourtables
Addingafield
Let’ssayyouhavecreatedyourtablebutforgottentocreatetheNAMEfield.Crisis!
Neverfear,asolutionisathand,withtheALTERTABLEcommand…
Typein: ALTERTABLE<tablename>(noteNOsemicolon)
ADD<fieldname><fieldtype>AFTER<existingfieldname>;
Sothiswouldlooklike:
ALTERTABLEpets
ADDfoodCHAR(30)AFTERsex
Or,whatifyouw
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年互聯(lián)網(wǎng)行業(yè)人才招募與培養(yǎng)服務合同
- 2025年醫(yī)養(yǎng)結合項目土地租賃及合作開發(fā)合同
- 2025年智能家用節(jié)能冰箱大宗采購合作協(xié)議
- 2025年企業(yè)數(shù)字化轉型項目財務總監(jiān)服務合同(AI賦能版)
- 2025年學校特色課程開發(fā)與教師專業(yè)成長服務全面合作協(xié)議
- 2025年度光伏玻璃生產(chǎn)線自動化升級改造合同
- 2025年度工商局企業(yè)股權質押貸款業(yè)務執(zhí)行細則合同
- 2025年能源優(yōu)化利用咨詢與管理服務合同
- 2025年跨境電商物流配送合同范本物流配送
- 2025年商用飛機機載導航系統(tǒng)性能檢測服務協(xié)議
- 多媒體教室使用的課件
- 2025年軍隊專業(yè)技能崗位文職人員招聘考試(工程機械駕駛員)歷年參考題庫含答案詳解(5卷)
- 2025年下半年廣西現(xiàn)代物流集團社會招聘校園招聘筆試參考題庫附帶答案詳解(10套)
- 2025年粉筆輔警考試題庫
- 2025年小學教研室教學計劃
- 2025年上海市建筑工程施工合同模板
- 手術室護理業(yè)務學習
- 高中英語必背3500單詞表完整版
- 牛的品種及生物學特性
- 阿特拉斯變頻無油螺桿空壓機說明書
- 口腔解剖生理學顳下頜關節(jié)精選課件
評論
0/150
提交評論