* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Databases - McMaster University
Information privacy law wikipedia , lookup
Predictive analytics wikipedia , lookup
Versant Object Database wikipedia , lookup
Business intelligence wikipedia , lookup
Operational transformation wikipedia , lookup
Relational algebra wikipedia , lookup
Data vault modeling wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
Clusterpoint wikipedia , lookup
EmilSekerinski,McMasterUniversity,WinterTerm16/17 COMPSCI1MD3IntroductiontoProgramming AnSQLquerygoesintoabar,walksuptotwotables andasks,"CanIjoinyou?" Likeprogramminglanguages,databasesallowtoprocessand storedata.However: ¡ dataisstoredindedicatedfilesandloadedasneeded:data canbemuchlargerthantheavailablememory(retailer catalogue,bankaccounts,personnelrecords);thereisno needtoexplicitlyopenfilesandreaddata ¡ datacanbeaccessed"simultaneously"by"clients" ¡ dataisatomicallyupdated:dataiseitherstoredornot,but neverbecomescorrupt,evenincaseoffailure(diskerror, networkdisconnection) ¡ datamustbestructuredinspecificways,e.g.astablesin relationaldatabases ¡ complexqueriescanbewritteninadedicatedquery language Dataitemsandtheirrelationshipisstoredintables.Atableisa collectionofrecords(objects,entities)withfields(attributes). Movie: MovieId Title Genre Rating 101 Casablanca dramaromance PG 102 BacktotheFuture comedyadventure PG 103 Monsters,Inc animationcomedy G 104 FieldofDreams fantasydrama PG 105 Alien sci-fihorror R 106 Unbreakable thriller PG-13 107 X-Men actionsci-fi PG-13 5022 Elisabeth dramaperiod R 5793 LifeofBrian comedy R 7442 12AngryMen drama PG Adatabaseschemaspecifiesthetypesofthefieldsofeachtable: ¡ INTEGER:upto8bytesintegers ¡ REAL:8bytefloats ¡ TEXT:Unicodestrings ¡ BOOLEAN:storedas0and1 ¡ DATE:storedasnumericvalue Aprimarykeyisafieldthatuniquelyidentifiesarecord.Thekey fieldsarespecifiedintheschema.Bydefault,fieldsareTEXT: Movie(MovieIDINTEGERPRIMARYKEY,Title,Genre,Rating) SQLiteisawidelyusedserverless(databasefilesarestored locally)relationaldatabasethatcomespreinstalledorcanbe downloadedatsqlite.org Allrelationaldatabaseshavesimilarcommands.Weshowthe useofSQLitefromthecommandlineandwithPython.For exampleintheMacOSXorLinuxcommandline: $ sqlite3 videostore.db SQLite version 3.8.5 2014-08-15 22:37:57 Enter ".help" for usage hints. sqlite> ... sqlite> .quit create table Table (Column [Type], …) insert into Table values (Expr, …) Allcommandshavetobeterminatedby; create table Movie(MovieId INTEGER PRIMARY KEY, Title, Genre, Rating); insert into Movie values(101, 'Casablanca', 'drama romance', 'PG'); insert into Movie values(102, 'Back to the Future', 'comedy adventure', 'PG'); insert into Movie values(103, 'Monsters, Inc', 'animation comedy', 'G'); insert into Movie values(101, 'Field of Dreams', 'fantasy drama', 'PG'); Error: UNIQUE constraint failed: Movie.MovieId Supposewewantkeeptrackwhichcustomerrentedwhichvideo: customersandtherentsrelationshipareexpressedastables CustomerId Name Address Customer: 101 DennisCook 123Broadwalk 102 DougNickle 456ParkPlace 103 RandyWolf 789PacificAvenue 104 AmyYao 321StJamesPlace 105 RobertMwanri 654MarvinGardens 106 DavidCoggin 987CharlesPlace CustomerId MovieId DateRented DueDate Rents: 103 104 3-12-2017 3-13-2017 103 5022 3-28-2017 3-29-2017 105 107 3-28-2017 3-29-2017 create table Customer(CustomerId INTEGER PRIMARY KEY, Name, Address); create table Rents(CustomerId INTEGER, MovieId INTEGER, DateRented DATE, DateDue DATE); insert into Customer values(101, 'Dennis Cook', '123 Broadwalk'); insert into Customer values(102, 'Doug Nickle', '456 Park Place'); ... insert into Rents values(103, 104, '3-12-2016', '3-13-2016'); insert into Rents values(103, 5022, '3-28-2016', '3-29-2016'); insert into Rents values(105, 107, '3-28-2016', '3-29-2016'); update Table set Column = Expr, … [where Expr] delete from Table [where Expr] Forexample: update Movie set Genre = 'thriller drama' where title = 'Unbreakable'; delete from Movie where Rating = 'R'; select Column, … from Table, … where Cond [order by Column, …] Allcolumns(fields)areselectedwith*;theconditionisaBooleanexpression thatcanhaveconstructsaslike: select * from Movie; select * from Customer; select * from Rents; select Name, Address from Customer; select * from Movie where Genre like '%comedy%'; select * from Movie where Rating = 'PG' order by Title; select Column, … from Table, … join Table [using(Column)] … where Cond [order by Column, …] Combinedresultofjoiningtables: select * from Customer join Rents using(CustomerId); select * from Customer join Rents using(CustomerId) join Movie using(MovieId); Allcustomernames,movietitles,andduedates: select Customer.Name, Movie.Title, Rents.DateDue from Customer join Rents using(CustomerId) join Movie using(MovieId); TitlesofallmoviesofRandyWolfwithduedates: select Movie.Title, Rents.DateDue from Customer join Rents using(CustomerId) join Movie using(MovieId) where Customer.Name = 'Randy Wolf'; Ifacustomerisdeletedwhohasstillvideosrented,thentheRentstablewould refertoacustomerthatdoesnotexist,whichisaninconsistencyinthe database.Triggerscanautomaticallyensurethiskindofconsistency: create trigger Name delete on Table [when Expr] begin statement; ... end Thestatementcanbeanyofinsert,delete,updateandoldcanbe usedtorefertothevaluewhichissupposedtobedeleted, create trigger delete_customer delete on Customer begin delete from Rents where Rents.customerid = old.customerid; end; delete from Customer where customerid = 103; willnowautomaticallyalsoexecute delete from Rents where Rents.customerid = 103; Triggerscanalsobecreatedforinsertionandupdates create trigger Name insert on Table [when Expr] begin statement; ... end create trigger Name update on Table [when Expr] begin statement; ... end Thestatementofaninsertionmayusenewtorefertothevaluetobe inserted,thestatementofanupdatemayuseoldandnewtorefertheold andnewvalue. SQLisastandardizedlanguagethatwasfirstproposedin1974 forCodd'srelationaldatamodelfrom1970.Besidesqueries (select)italsosupportsmanipulation(create,insert, update,delete,…)transactions(begin,commit, rollback),authorization,programmingconstructs SQLismoregeneralthantheexamplessuggest,e.g.theresult ofanSQLquerymaybetheinputofanotherone. Alloftoday'srelationaldatabasessupportSQL,withvariations. Morerecently,also"NoSQL"databasesfordifferently structureddataandcloudstoragearebecomingpopular. Programscanstoredatainfileswiththebuild-infunctions; alternatively,programscanstoredatainadatabase.Pythonhas alibrarymodulethroughwhichanSQLite3databasecanbe accessed: import sqlite3 db = sqlite3.connect('…/videostore.db') ... db.close() Dataisconvertedasfollows: null ↔︎ None integer ↔︎ int real ↔︎ float text ↔︎ str AllSQLstatementsarepassedasstringtothedatabase.Acursoris neededtoiterateovertheresultsofanSQLquery: c = db.cursor() c.execute('select * from Customer order by Name') print(c.fetchone()) Ifthereisnoresult,Noneisreturned.SeveralSQLrowscanbe retrievedasalistoftuples c.execute('select * from Customer order by Name') print(c.fetchall()) Acursorcanusedasaniterator: for row in c.execute('select * from Customer'): print(row) SQLdatamanipulationstatementsdonothaveaneffectrightaway,onlyafter commit. c.execute("insert into Customer values(103, 'Randy Wolf', '789 Pacific Avenue')") db.commit() c.execute("delete from Customer where CustomerId = 103") db.commit() SinceconstructingSQLstringsistedious,aspecialformatinsupported,inwhich? inSQLarereplaced def insert_customer(db, customerid, name, address): c = db.cursor() c.execute("insert into Customer values(?, ?, ?)", \ (customerid, name, address)) db.commit() insert_customer(db, 103, 'Randy Wolf', \ '789 Pacific Avenue')