├── Chapter01 ├── Activity 1 │ └── Table Formats.xlsx └── Exercise 1 │ └── Table Definitions.xlsx ├── Chapter02 ├── Excercise 2.03 │ └── Chapter2 Ancilliary Tables.sql ├── Excercise 2.07 │ └── autoclub.mwb ├── Excercise 2.08 │ └── autoclub.mwb └── Images │ ├── Image1.png │ └── Image2.png ├── Chapter03 ├── Activity01 │ └── Solution to Activity 2 – Create table with Indexes and Foreign Keys.txt ├── Activity02 │ ├── Activity 5 – Determining YOUR MemberID.txt │ ├── MemberPhoto_2.jpg │ ├── Solution for Activity 5 – Adding Image file paths to the database - (3).txt │ ├── Solution for Activity 5 – Adding Image file paths to the database - (4).txt │ └── Solution for Activity 5 – Adding Image file paths to the database.docx ├── Exercise03 │ └── Exercise 3 – Creating a new database .txt ├── Exercise04 │ └── Exercise 4 - Creating a new table.txt ├── Exercise05 │ └── Exercise 5 – Creating a new table with Indexes and Foreign Keys.txt ├── Exercise06 │ └── Exercise 6 – Modify and existing table.txt ├── Exercise07 │ └── Exercise 7 – Adding a single record.txt ├── Exercise08 │ └── Exercise 9 – Updating a record.txt ├── Exercise09 │ ├── Exercise 10 – Files and blobs - (1) Secure File Path.txt │ ├── Exercise 10 – Files and blobs - (4) UPDATE MEMBERS.txt │ ├── FredBloggs_Phtoto.jpg │ └── FredBloggs_Signature.JPG ├── Exercise10 │ ├── Exercise 11 – Files and file paths - Part 2 – Storing the root path.txt │ ├── Exercise 11 – Files and file paths - Part 3 – Storing Freds Image Paths.txt │ ├── Exercise 11 – Files and file paths - Part 4 – Extracting the full image path.txt │ ├── MemberPhoto_1.jpg │ └── MemberSignature_1.JPG ├── autoclub │ └── autoclub database - Exercise 7.sql └── images │ └── MemberPhoto_2.jpg ├── Chapter04 ├── .gitignore ├── Activity01 │ ├── CoffeeProducts.xlsx │ ├── ch12_Activity_4_01.sql │ └── worldcol.js ├── Exercise01 │ └── ch4_Excercise_4_01.sql ├── Exercise02 │ └── ch4_Excercise_4_02.sql ├── Exercise03 │ └── ch4_Excercise_4_03.sql ├── Exercise04 │ └── ch4_Excercise_4_04.sql ├── Exercise05 │ └── ch4_Excercise_4_05.sql └── worldcol.js ├── Chapter05 ├── Activity5.01 │ └── ch5_Activity_5_1.sql ├── Activity5.02 │ └── Ch5_Activity5_02.sql ├── Exercise5.01 │ └── ch5_Excercise_5_1.sql ├── Exercise5.02 │ └── ch5_Excercise_5_2.sql ├── Exercise5.03 │ └── ch5_Excercise_5_3.sql └── Exercise5.04 │ └── ch5_Excercise_5_4.sql ├── Chapter06 ├── Activity01 │ └── Solution to Activity 2 – Updating data in a View.sql ├── Exercise01 │ └── Exercise 01 – Creating a Mailing List with a View.sql ├── Exercise02 │ └── Exercise 4 – Creating a function.sql ├── Exercise03 │ ├── Exercise 8 – Creating a Stored Procedure.sql │ └── Test Script Exercise 8 – Creating a Stored Procedure.sql ├── Exercise04 │ ├── Exercise 9 – Stored Procedure with parameters.sql │ └── Test Script Exercise 9 – Stored Procedure with parameters.sql ├── Exercise05 │ ├── Exercise 10 – IN and INOUT.sql │ └── Test Script Exercise 10 – IN and INOUT.sql ├── Exercise06 │ ├── Check Test Members Age.sql │ ├── Create Business Rule.sql │ ├── Create CheckMemberAge Trigger.sql │ ├── Prepare MyISAM version of members table.sql │ ├── Test - Fail - CheckMemberAge.sql │ └── Test - Success - CheckMemberAge.sql └── Exercise07 │ └── ch6_Excercise_7_01.sql ├── Chapter07 ├── Activity7.01 │ ├── Activity_5_01_Solution_Create_Database.js │ ├── Activity_5_01_Solution_Create_Tables.js │ ├── Requirements.txt │ └── mysqlconnection.js ├── Databases │ ├── GP_PracticeDatabase.sql │ ├── PracticeDatabase 20190926a.sql │ ├── PracticeDatabaseNoSchema 20190926a.sql │ ├── mysqlconnection1.js │ └── mysqlconnection2.js ├── Exercise7.01 │ └── exercise.sql ├── Exercise7.02 │ └── Add-OutToConsole.js ├── Exercise7.03 │ └── Add-OutToBrowser.js ├── Exercise7.04 │ ├── Log-ToDiskFile.js │ └── Log.txt ├── Exercise7.05 │ └── MySQLConnection.js ├── Exercise7.06 │ ├── MySQLConnection.js │ └── TestModule.js ├── Exercise7.07 │ └── MySQLCreateDatabase.js ├── Exercise7.08 │ └── MySQLCreateTable.js ├── mysqlconnection.js └── node_modules.zip ├── Chapter08 ├── Activity8.01 │ ├── Activity-MultipleUpdates.js │ ├── CountryDetails.sql │ ├── CountryPopulation2004_2018.sql │ └── back_CountryDetails.sql ├── Activity8.02 │ └── Activity_6_02_Solution_Populate_Tables.js ├── Exercise8.01 │ └── MySQLInsertOneRecord.js ├── Exercise8.02 │ └── MySQLInsertMultipleRecordsContinents.js ├── Exercise8.03 │ └── MySQLInsertMultipleFieldRecords.js ├── Exercise8.04 │ └── UpdateOneRecord.js ├── Exercise8.05 │ └── TotalPopulationByContinent.js └── mysqlconnection.js ├── Chapter09 ├── Exercise9.01 │ ├── MS Access Training Data.mdb │ └── MySQL Training Database.accdt └── Exercise9.06 │ ├── Convert ms_access_migration to UTF8.sql │ └── Create Collation Conversion commands.sql ├── Chapter10 ├── Activity10.01 │ ├── Create Function fnCountGroups.sql │ └── fnCountGroups.bas ├── Activity10.02 │ ├── Create Function fnCountGroups.sql │ └── Create Function fnCountSeries.sql ├── Activity10.03 │ ├── Create Procedure spCountryList.sql │ ├── Create Procedure spGroupsList.sql │ └── spGroupsList and spCountryList.bas ├── Activity10.04 │ └── Solution The Parameterized Stored Procedure – Series List.bas ├── Activity10.05 │ ├── Create Procedure spCountryList_par.sql │ ├── Create Procedure spDateRange_par.sql │ └── spDateRange_par.bas ├── Exercise10.02 │ └── Create Function fnCountSeries.sql ├── Exercise10.03 │ └── Create Procedure spSeriesList.sql ├── Exercise10.04 │ └── Create Procedure spSeriesList_par.sql ├── Exercise10.05 │ ├── CONCAT sample.bas │ ├── Create Procedure spCountryList_par.sql │ ├── Exercise 8_05 SELECT Case.bas │ ├── Final VBA Code to run the procedure.bas │ └── Test spCountryList.bas ├── Exercise10.06 │ └── Create Procedure spCTSource_par.sql └── Exercise10.07 │ └── Exercise 8_07_10.bas ├── Chapter11 ├── Activity11.01 │ └── Global Connection VBA.bas ├── Activity11.02 │ └── Solution for Activity – Artist_Units_Sold.bas ├── Activity11.03 │ └── Solution for Activity – Artist Dropdown.bas ├── Activity11.04 │ └── Solution for Activity – Create Chart – Artist Trac.bas ├── Chinook.sql ├── Exercise11.08 │ └── Exercise – Creating a Connection Function.bas ├── Exercise11.09 │ └── Exercise – Read Genre Sales.bas ├── Exercise11.11 │ └── Workbook_Opoen Code.bas ├── Exercise11.12 │ └── Exercise – Load Genre Sales Chart Data.bas ├── Exercise9.13 │ └── Exercise – Populate Genre Sales Chart.bas └── MySQL Excel Training Template.xlsm ├── Chapter12 ├── Activity01 │ └── CoffeeProducts.xlsx ├── Exercise12.01 │ └── Exercise – Create the Named DSN Connection function.bas ├── Exercise12.02 │ └── Exercise – GenreTrackSalesStats Function.bas └── Exercise12.03 │ ├── Exercise – Generic Data Reader Part 2.bas │ └── Exercise – Generic Data Reader.bas ├── Chapter13 ├── .gitignore ├── Activity01 │ └── ch11_Activity_01.sql ├── Activity02 │ └── ch11_Activity_02.js ├── Activity03 │ ├── building1.sql │ ├── building2.CSV │ ├── building3.json │ └── ch11_Activity_03.js ├── Activity04 │ └── ch11_Activity_04.sql ├── Exercise01 │ └── ch11_Excercise_8_01.sql ├── Exercise02 │ └── ch11_Excercise_8_02.sql ├── Exercise03 │ └── ch11_Excercise_8_03.sql ├── Exercise04 │ └── ch11_Excercise_8_04.sql ├── Exercise05 │ └── ch11_Excercise_8_05.sql ├── Exercise06 │ └── ch11_Excercise_8_06.js ├── Exercise07 │ └── ch11_Excercise_8_07.js ├── Exercise08 │ └── ch11_Excercise_8_08.sql ├── Exercise09 │ └── ch11_Exercise_8_09.sql ├── Exercise10 │ └── ch11_Excercise_8_10.sql ├── Exercise11 │ ├── ch11_Excercise_8_11.js │ └── the_beatles.json ├── Exercise12 │ └── ch11_Excercise_8_12.sql ├── Exercise13 │ └── ch11_Excercise_8_13.sql ├── World │ └── world.sql └── XDEV │ ├── animals.sql │ └── ch08_02_X_DevApi.py ├── Chapter14 ├── Activity16.01 │ └── ch16_activity_01.sql ├── Exercise16.01 │ └── ch16_excercise_16_01.sql ├── Exercise16.02 │ └── ch16_excercise_16_02.sql └── Exercise16.03 │ └── ch16_excercise_16_03.sql ├── Chapter15 ├── .gitignore ├── Activity17.01 │ ├── ch17_Activity_01.bat │ └── ch17_Activity_01.sql ├── Activity17.02 │ ├── ch17_Activity_02.bat │ └── ch17_Activity_02.sql ├── Exercise17.01 │ ├── ch17_Excercise_17_01.sql │ ├── ch17_Exercise_17_01_dump.bat │ └── ch17_Exercise_17_01_fulldump.bat ├── Exercise17.02 │ └── ch17_Exercise_17_02_backup_pump.bat └── Exercise17.03 │ ├── ch17_Exercise_17_03_restore_backup.bat │ └── ch17_Exercise_17_03_restore_backup.sql ├── LICENSE └── README.md /Chapter01/Activity 1/Table Formats.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter01/Activity 1/Table Formats.xlsx -------------------------------------------------------------------------------- /Chapter01/Exercise 1/Table Definitions.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter01/Exercise 1/Table Definitions.xlsx -------------------------------------------------------------------------------- /Chapter02/Excercise 2.07/autoclub.mwb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter02/Excercise 2.07/autoclub.mwb -------------------------------------------------------------------------------- /Chapter02/Excercise 2.08/autoclub.mwb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter02/Excercise 2.08/autoclub.mwb -------------------------------------------------------------------------------- /Chapter02/Images/Image1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter02/Images/Image1.png -------------------------------------------------------------------------------- /Chapter02/Images/Image2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter02/Images/Image2.png -------------------------------------------------------------------------------- /Chapter03/Activity01/Solution to Activity 2 – Create table with Indexes and Foreign Keys.txt: -------------------------------------------------------------------------------- 1 | -- ----------------------------------------------------- 2 | -- Table `autoclub`.`eventmemberregistration` 3 | -- ----------------------------------------------------- 4 | CREATE TABLE IF NOT EXISTS `autoclub`.`eventmemberregistration` ( 5 | `ID` INT NOT NULL AUTO_INCREMENT, 6 | `ClubEventID` INT NOT NULL, 7 | `MemberID` INT NOT NULL, 8 | `ExpectedGuestCount` INT NOT NULL DEFAULT 0, 9 | `RegistrationDate` DATE NOT NULL, 10 | `FeesPaid` BIT NOT NULL DEFAULT 0, 11 | `TotalFees` DOUBLE NOT NULL DEFAULT 0, 12 | `MemberAttended` BIT NOT NULL DEFAULT 0, 13 | `ActualGuestCount` INT NOT NULL DEFAULT 0, 14 | `Notes` MEDIUMTEXT NULL, 15 | `WhenAdded` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, 16 | `LastModified` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 17 | PRIMARY KEY (`ID`), 18 | INDEX `Idx_EventID` (`ClubEventID` DESC), 19 | INDEX `FK_EventReg_Members_idx` (`MemberID` ASC), 20 | CONSTRAINT `FK_EventReg_ClubEvents` 21 | FOREIGN KEY (`ClubEventID`) 22 | REFERENCES `autoclub`.`clubevents` (`ID`) 23 | ON DELETE NO ACTION 24 | ON UPDATE NO ACTION, 25 | CONSTRAINT `FK_EventReg_Members` 26 | FOREIGN KEY (`MemberID`) 27 | REFERENCES `autoclub`.`members` (`ID`) 28 | ON DELETE NO ACTION 29 | ON UPDATE NO ACTION) 30 | ENGINE = InnoDB; 31 | -------------------------------------------------------------------------------- /Chapter03/Activity02/Activity 5 – Determining YOUR MemberID.txt: -------------------------------------------------------------------------------- 1 | SELECT ID FROM members where `Surname` = "Pettit" -------------------------------------------------------------------------------- /Chapter03/Activity02/MemberPhoto_2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter03/Activity02/MemberPhoto_2.jpg -------------------------------------------------------------------------------- /Chapter03/Activity02/Solution for Activity 5 – Adding Image file paths to the database - (3).txt: -------------------------------------------------------------------------------- 1 | UPDATE `members` 2 | SET 3 | PhotoPath = "Members\\Photos\\MemberPhoto_2.jpg" 4 | WHERE `ID`=2; 5 | -------------------------------------------------------------------------------- /Chapter03/Activity02/Solution for Activity 5 – Adding Image file paths to the database - (4).txt: -------------------------------------------------------------------------------- 1 | SELECT CONCAT((SELECT `Value` FROM `lookups` WHERE `Key`="ImageRepository") , `PhotoPath`) AS FullPhotoPath 2 | FROM `members` WHERE `members`.`ID`=2 3 | -------------------------------------------------------------------------------- /Chapter03/Activity02/Solution for Activity 5 – Adding Image file paths to the database.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter03/Activity02/Solution for Activity 5 – Adding Image file paths to the database.docx -------------------------------------------------------------------------------- /Chapter03/Exercise03/Exercise 3 – Creating a new database .txt: -------------------------------------------------------------------------------- 1 | CREATE SCHEMA `shoporder`; 2 | -------------------------------------------------------------------------------- /Chapter03/Exercise04/Exercise 4 - Creating a new table.txt: -------------------------------------------------------------------------------- 1 | -- ----------------------------------------------------- 2 | -- Table `autoclub`.`user` 3 | -- ----------------------------------------------------- 4 | CREATE TABLE IF NOT EXISTS `autoclub`.`user` ( 5 | `ID` INT NOT NULL AUTO_INCREMENT, 6 | `username` VARCHAR(16) NOT NULL, 7 | `email` VARCHAR(255) NULL, 8 | `password` VARCHAR(32) NOT NULL, 9 | `Active` BIT NOT NULL DEFAULT 1, 10 | `WhenAdded` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, 11 | `LastModified` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 12 | PRIMARY KEY (`ID`)); -------------------------------------------------------------------------------- /Chapter03/Exercise05/Exercise 5 – Creating a new table with Indexes and Foreign Keys.txt: -------------------------------------------------------------------------------- 1 | -- ----------------------------------------------------- 2 | -- Table `autoclub`.`eventvenues` 3 | -- ----------------------------------------------------- 4 | CREATE TABLE IF NOT EXISTS `autoclub`.`eventvenues` ( 5 | `ID` INT NOT NULL AUTO_INCREMENT, 6 | `VenueName` VARCHAR(100) NOT NULL, 7 | `VenueAddress1` VARCHAR(255) NULL, 8 | `VenueAddress2` VARCHAR(255) NULL, 9 | `VenueTown` VARCHAR(30) NULL, 10 | `VenueState` INT NULL, 11 | `VenuePostcode` VARCHAR(10) NULL, 12 | `VenueContactName` VARCHAR(20) NULL, 13 | `VenuePhone` VARCHAR(15) NULL, 14 | `VenueEmail` VARCHAR(255) NULL, 15 | `VenueWebsite` VARCHAR(255) NULL, 16 | PRIMARY KEY (`ID`), 17 | INDEX `FK_EventVenue_States_idx` (`VenueState` ASC), 18 | UNIQUE INDEX `Idx_VenueName` (`VenueName` ASC), 19 | CONSTRAINT `FK_EventVenue_States` 20 | FOREIGN KEY (`VenueState`) 21 | REFERENCES `autoclub`.`states` (`ID`) 22 | ON DELETE RESTRICT 23 | ON UPDATE RESTRICT) 24 | ENGINE = InnoDB; 25 | 26 | 27 | -- ----------------------------------------------------- 28 | -- Table `autoclub`.`clubevents` 29 | -- ----------------------------------------------------- 30 | CREATE TABLE IF NOT EXISTS `autoclub`.`clubevents` ( 31 | `ID` INT NOT NULL AUTO_INCREMENT, 32 | `EventType` INT NULL, 33 | `EventDate` DATE NOT NULL COMMENT 'Date of the event', 34 | `EventStartTime` TIME NOT NULL COMMENT 'Time the event will start', 35 | `EventEndTime` TIME NOT NULL COMMENT 'Expected time the event will finish', 36 | `RegistrationTime` TIME NOT NULL COMMENT 'Members must register on the day by this time', 37 | `VenueStart` INT NOT NULL COMMENT 'Venue or location where the event will start from', 38 | `VenuEnd` INT NOT NULL COMMENT 'Venue or location where the event will end', 39 | `EntriesClose` DATETIME NULL COMMENT 'Date and Time when entry registrations close', 40 | `EntryFee` DOUBLE NOT NULL DEFAULT 0, 41 | `EventTitle` VARCHAR(150) NOT NULL, 42 | `EventBlurb` MEDIUMTEXT NULL, 43 | `clubeventscol` VARCHAR(45) NULL, 44 | PRIMARY KEY (`ID`), 45 | INDEX `FK_ClubEvents_EventVenue_idx` (`VenueStart` ASC), 46 | INDEX `FK_ClubEvents_EventVenue_End_idx` (`VenuEnd` ASC), 47 | INDEX `Idx_EventDate` (`EventDate` DESC), 48 | CONSTRAINT `FK_ClubEvents_EventVenue_Start` 49 | FOREIGN KEY (`VenueStart`) 50 | REFERENCES `autoclub`.`eventvenues` (`ID`) 51 | ON DELETE RESTRICT 52 | ON UPDATE RESTRICT, 53 | CONSTRAINT `FK_ClubEvents_EventVenue_End` 54 | FOREIGN KEY (`VenuEnd`) 55 | REFERENCES `autoclub`.`eventvenues` (`ID`) 56 | ON DELETE RESTRICT 57 | ON UPDATE RESTRICT) 58 | ENGINE = InnoDB; 59 | 60 | 61 | -- ----------------------------------------------------- 62 | -- Table `autoclub`.`eventtype` 63 | -- ----------------------------------------------------- 64 | CREATE TABLE IF NOT EXISTS `autoclub`.`eventtype` ( 65 | `ID` INT NOT NULL AUTO_INCREMENT, 66 | `EventType` VARCHAR(45) NULL, 67 | PRIMARY KEY (`ID`)) 68 | ENGINE = InnoDB; 69 | -------------------------------------------------------------------------------- /Chapter03/Exercise06/Exercise 6 – Modify and existing table.txt: -------------------------------------------------------------------------------- 1 | CREATE UNIQUE INDEX `idx_username` ON `autoclub`.`user` (`username`); 2 | 3 | ALTER TABLE `clubevents` 4 | ADD CONSTRAINT `FK_Clubevents_EventType` 5 | FOREIGN KEY (`EventType`) REFERENCES `EventType`(`ID`); 6 | -------------------------------------------------------------------------------- /Chapter03/Exercise07/Exercise 7 – Adding a single record.txt: -------------------------------------------------------------------------------- 1 | INSERT INTO members (`Surname`,`FirstName`,`DOB`,`JoinDate`) 2 | SELECT "Bloggs","Frederick","1990/06/15","2020/01/15"; 3 | -------------------------------------------------------------------------------- /Chapter03/Exercise08/Exercise 9 – Updating a record.txt: -------------------------------------------------------------------------------- 1 | UPDATE members 2 | SET 3 | active = 0, 4 | InactiveDate = CURRENT_DATE() 5 | WHERE 6 | ID=1; 7 | -------------------------------------------------------------------------------- /Chapter03/Exercise09/Exercise 10 – Files and blobs - (1) Secure File Path.txt: -------------------------------------------------------------------------------- 1 | SHOW VARIABLES LIKE "secure_file_priv"; -------------------------------------------------------------------------------- /Chapter03/Exercise09/Exercise 10 – Files and blobs - (4) UPDATE MEMBERS.txt: -------------------------------------------------------------------------------- 1 | UPDATE `members` 2 | SET 3 | active = 1, 4 | InactiveDate = NULL, 5 | Signature = LOAD_File('C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/Fred Bloggs_Signature.JPG'), 6 | Photo = LOAD_File('C:\\ProgramData\\MySQL\\MySQL Server 8.0\\Uploads\\Fred Bloggs_Photo.JPG') 7 | WHERE `ID`=1; 8 | -------------------------------------------------------------------------------- /Chapter03/Exercise09/FredBloggs_Phtoto.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter03/Exercise09/FredBloggs_Phtoto.jpg -------------------------------------------------------------------------------- /Chapter03/Exercise09/FredBloggs_Signature.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter03/Exercise09/FredBloggs_Signature.JPG -------------------------------------------------------------------------------- /Chapter03/Exercise10/Exercise 11 – Files and file paths - Part 2 – Storing the root path.txt: -------------------------------------------------------------------------------- 1 | INSERT INTO lookups 2 | (`Key`,`Value`,`Descriptions`) 3 | SELECT 4 | "ImageRepository", 5 | "D:\\FileRepository\\", 6 | "Automobile Club images"; 7 | -------------------------------------------------------------------------------- /Chapter03/Exercise10/Exercise 11 – Files and file paths - Part 3 – Storing Freds Image Paths.txt: -------------------------------------------------------------------------------- 1 | UPDATE `members` 2 | SET 3 | SigPath = "Members\\Signatures\\MemberSignature_1.jpg", 4 | PhotoPath = "Members\\Photos\\MemberPhoto_1.jpg" 5 | WHERE `ID`=1; 6 | -------------------------------------------------------------------------------- /Chapter03/Exercise10/Exercise 11 – Files and file paths - Part 4 – Extracting the full image path.txt: -------------------------------------------------------------------------------- 1 | SELECT `FirstName`,`Surname`, 2 | 3 | CONCAT((SELECT `Value` FROM `lookups` WHERE `Key`="ImageRepository") , `PhotoPath`) AS FullPhotoPath, 4 | CONCAT((SELECT `Value` FROM `lookups` WHERE `Key`="ImageRepository") , `SigPath`) AS FullSignaturePath 5 | 6 | FROM `members` WHERE `members`.`ID`=1 7 | -------------------------------------------------------------------------------- /Chapter03/Exercise10/MemberPhoto_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter03/Exercise10/MemberPhoto_1.jpg -------------------------------------------------------------------------------- /Chapter03/Exercise10/MemberSignature_1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter03/Exercise10/MemberSignature_1.JPG -------------------------------------------------------------------------------- /Chapter03/images/MemberPhoto_2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter03/images/MemberPhoto_2.jpg -------------------------------------------------------------------------------- /Chapter04/.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | *.reject 3 | -------------------------------------------------------------------------------- /Chapter04/Activity01/CoffeeProducts.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter04/Activity01/CoffeeProducts.xlsx -------------------------------------------------------------------------------- /Chapter04/Activity01/ch12_Activity_4_01.sql: -------------------------------------------------------------------------------- 1 | USE world; 2 | 3 | SELECT Name, Population FROM city ORDER BY Population LIMIT 1; 4 | 5 | SELECT Code FROM country WHERE name='India'; 6 | SELECT * FROM countrylanguage WHERE CountryCode='IND'; 7 | 8 | SELECT Language FROM countrylanguage GROUP BY Language HAVING COUNT(*)>20; 9 | 10 | SELECT name 11 | FROM world.country 12 | WHERE region = "Southern and Central Asia" 13 | ORDER BY population DESC 14 | LIMIT 5; 15 | 16 | SELECT * FROM city WHERE Name Like '%ester'; 17 | -------------------------------------------------------------------------------- /Chapter04/Activity01/worldcol.js: -------------------------------------------------------------------------------- 1 | \use world 2 | 3 | db.dropCollection('worldcol') 4 | 5 | db.createCollection('worldcol') 6 | 7 | \sql INSERT INTO worldcol(doc) SELECT JSON_OBJECT('_id', city.id, 'name', city.name, 'district', city.district, 'population', city.population, 'is_capital', CAST(country.capital=city.id AS JSON), 'country', json_object('name', country.name, 'code', country.code, 'region', country.region, 'continent', country.continent, 'surface_area', country.surfacearea, 'independence_year', country.indepyear, 'population', country.population, 'GNP', country.gnp, 'local_name', country.localname, 'government_form', country.governmentform, 'head_of_state', country.headofstate, 'code2', country.code2), 'language', json_objectagg(countrylanguage.language, json_object('is_official', CAST(countrylanguage.isofficial='T' AS JSON), 'percentage', countrylanguage.percentage))) AS 'city_json' FROM city LEFT JOIN country ON city.CountryCode=country.Code LEFT JOIN countrylanguage ON city.CountryCode=countrylanguage.CountryCode GROUP BY city.id 8 | -------------------------------------------------------------------------------- /Chapter04/Exercise01/ch4_Excercise_4_01.sql: -------------------------------------------------------------------------------- 1 | USE world; 2 | 3 | DESCRIBE countrylanguage; 4 | 5 | SELECT Language FROM countrylanguage LIMIT 5; 6 | -------------------------------------------------------------------------------- /Chapter04/Exercise02/ch4_Excercise_4_02.sql: -------------------------------------------------------------------------------- 1 | USE world; 2 | 3 | DESCRIBE country; 4 | 5 | SELECT Name, SurfaceArea FROM country WHERE Region='Western Europe'; 6 | -------------------------------------------------------------------------------- /Chapter04/Exercise03/ch4_Excercise_4_03.sql: -------------------------------------------------------------------------------- 1 | USE world; 2 | 3 | SELECT Name, IndepYear, Population, SurfaceArea FROM country 4 | WHERE YEAR(NOW()) - IndepYear > 1000; 5 | 6 | SELECT 7 | Name, 8 | IndepYear, 9 | YEAR(NOW()) - IndepYear, 10 | Population, 11 | ROUND(Population/SurfaceArea,0) 12 | FROM country 13 | WHERE YEAR(NOW()) - IndepYear > 1000; 14 | 15 | SELECT 16 | Name, 17 | IndepYear, 18 | YEAR(NOW()) - IndepYear, 19 | ROUND(Population / 1000000, 0), 20 | ROUND(Population/SurfaceArea,0) 21 | FROM country 22 | WHERE YEAR(NOW()) - IndepYear > 1000; 23 | -------------------------------------------------------------------------------- /Chapter04/Exercise04/ch4_Excercise_4_04.sql: -------------------------------------------------------------------------------- 1 | USE world; 2 | 3 | SELECT Continent, AVG(GNP), SUM(SurfaceArea) 4 | FROM country GROUP BY Continent; 5 | 6 | SELECT Region, SUM(SurfaceArea) FROM country 7 | WHERE Continent='Asia' GROUP BY Region; 8 | -------------------------------------------------------------------------------- /Chapter04/Exercise05/ch4_Excercise_4_05.sql: -------------------------------------------------------------------------------- 1 | SELECT Name, CASE WHEN population < 100000 THEN 'small' 2 | WHEN population < 500000 then 'medium' 3 | ELSE 'large' END AS countrySize 4 | FROM world.country; -------------------------------------------------------------------------------- /Chapter04/worldcol.js: -------------------------------------------------------------------------------- 1 | \use world 2 | 3 | db.dropCollection('worldcol') 4 | 5 | db.createCollection('worldcol') 6 | 7 | \sql INSERT INTO worldcol(doc) SELECT JSON_OBJECT('_id', city.id, 'name', city.name, 'district', city.district, 'population', city.population, 'is_capital', CAST(country.capital=city.id AS JSON), 'country', json_object('name', country.name, 'code', country.code, 'region', country.region, 'continent', country.continent, 'surface_area', country.surfacearea, 'independence_year', country.indepyear, 'population', country.population, 'GNP', country.gnp, 'local_name', country.localname, 'government_form', country.governmentform, 'head_of_state', country.headofstate, 'code2', country.code2), 'language', json_objectagg(countrylanguage.language, json_object('is_official', CAST(countrylanguage.isofficial='T' AS JSON), 'percentage', countrylanguage.percentage))) AS 'city_json' FROM city LEFT JOIN country ON city.CountryCode=country.Code LEFT JOIN countrylanguage ON city.CountryCode=countrylanguage.CountryCode GROUP BY city.id 8 | -------------------------------------------------------------------------------- /Chapter05/Activity5.01/ch5_Activity_5_1.sql: -------------------------------------------------------------------------------- 1 | USE sakila; 2 | 3 | SELECT COUNT(*) 4 | FROM film f 5 | JOIN inventory i ON f.film_id=i.film_id 6 | WHERE f.rating='PG'; 7 | 8 | SELECT f.title 9 | FROM film f 10 | JOIN film_actor fa ON f.film_id=fa.film_id 11 | JOIN actor a ON a.actor_id=fa.actor_id 12 | WHERE a.first_name='EMILY' AND a.last_name='DEE'; 13 | 14 | SELECT c.first_name, c.last_name, COUNT(*) FROM rental r 15 | JOIN customer c ON r.customer_id=c.customer_id 16 | GROUP BY c.customer_id ORDER BY COUNT(*) DESC LIMIT 1; 17 | 18 | SELECT f.title, SUM(p.amount) 19 | FROM payment p 20 | JOIN rental r ON p.rental_id=r.rental_id 21 | JOIN inventory i ON i.inventory_id=r.inventory_id 22 | JOIN film f ON f.film_id=i.film_id 23 | GROUP by f.film_id 24 | ORDER BY SUM(p.amount) DESC LIMIT 1; 25 | 26 | SELECT email 27 | FROM customer cu 28 | JOIN address a ON cu.address_id=a.address_id 29 | JOIN city ci ON ci.city_id=a.city_id 30 | JOIN country co ON co.country_id=ci.country_id 31 | WHERE country='Turkmenistan'\G 32 | -------------------------------------------------------------------------------- /Chapter05/Activity5.02/Ch5_Activity5_02.sql: -------------------------------------------------------------------------------- 1 | USE sakila; 2 | 3 | WITH films_in_range AS ( 4 | SELECT * FROM film 5 | WHERE release_year BETWEEN 2005 AND 2010) 6 | 7 | SELECT release_year, COUNT(release_year) 8 | FROM films_in_range; -------------------------------------------------------------------------------- /Chapter05/Exercise5.01/ch5_Excercise_5_1.sql: -------------------------------------------------------------------------------- 1 | USE world; 2 | 3 | SELECT ci.Name, ci.Population 4 | FROM city ci JOIN country co ON ci.CountryCode=co.Code 5 | WHERE co.Region='Middle East' ORDER BY ci.Population DESC LIMIT 5; 6 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.02/ch5_Excercise_5_2.sql: -------------------------------------------------------------------------------- 1 | USE world; 2 | 3 | SELECT * FROM countrylanguage 4 | WHERE Language='Portuguese' AND IsOfficial='T'; 5 | 6 | SELECT ( 7 | SELECT Name FROM country 8 | WHERE Code=CountryCode 9 | ) AS CountryName FROM countrylanguage 10 | WHERE Language='Portuguese' AND IsOfficial='T'; 11 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.03/ch5_Excercise_5_3.sql: -------------------------------------------------------------------------------- 1 | USE world; 2 | 3 | WITH country_portuguese AS ( 4 | SELECT CountryCode FROM countrylanguage 5 | WHERE Language='Portuguese' AND IsOfficial='T' 6 | ) 7 | SELECT * FROM country_portuguese; 8 | 9 | WITH country_portuguese AS ( 10 | SELECT CountryCode FROM countrylanguage 11 | WHERE Language='Portuguese' AND IsOfficial='T' 12 | ) 13 | SELECT 14 | * 15 | FROM country_portuguese col_pt 16 | JOIN countrylanguage col 17 | ON col_pt.CountryCode=col.CountryCode; 18 | 19 | WITH country_portuguese AS ( 20 | SELECT CountryCode FROM countrylanguage 21 | WHERE Language='Portuguese' AND IsOfficial='T' 22 | ) 23 | SELECT 24 | co.Name, 25 | GROUP_CONCAT(Language) AS Languages 26 | FROM country_portuguese col_pt 27 | JOIN countrylanguage col 28 | ON col_pt.CountryCode=col.CountryCode 29 | JOIN country co 30 | ON co.Code=col.CountryCode 31 | GROUP BY co.Name; 32 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.04/ch5_Excercise_5_4.sql: -------------------------------------------------------------------------------- 1 | USE world; 2 | 3 | EXPLAIN SELECT cl.Language, cl.Percentage 4 | FROM city ci JOIN country co ON ci.CountryCode=co.Code 5 | JOIN countrylanguage cl ON cl.CountryCode=co.Code 6 | WHERE 7 | ci.Name='San Francisco' 8 | AND co.Name='United States' 9 | AND cl.Percentage>1\G 10 | 11 | ALTER TABLE country ADD INDEX(Name); 12 | EXPLAIN SELECT cl.Language, cl.Percentage 13 | FROM city ci JOIN country co ON ci.CountryCode=co.Code 14 | JOIN countrylanguage cl ON cl.CountryCode=co.Code 15 | WHERE 16 | ci.Name='San Francisco' 17 | AND co.Name='United States' 18 | AND cl.Percentage>1\G 19 | 20 | ALTER TABLE city ADD INDEX (Name); 21 | EXPLAIN SELECT cl.Language, cl.Percentage 22 | FROM city ci JOIN country co ON ci.CountryCode=co.Code 23 | JOIN countrylanguage cl ON cl.CountryCode=co.Code 24 | WHERE 25 | ci.Name='San Francisco' 26 | AND co.Name='United States' 27 | AND cl.Percentage>1\G 28 | 29 | EXPLAIN SELECT cl.Language, cl.Percentage 30 | FROM city ci 31 | JOIN countrylanguage cl ON cl.CountryCode=ci.CountryCode 32 | WHERE 33 | ci.Name='San Francisco' 34 | AND cl.Percentage>1\G 35 | -------------------------------------------------------------------------------- /Chapter06/Activity01/Solution to Activity 2 – Updating data in a View.sql: -------------------------------------------------------------------------------- 1 | UPDATE vw_members_all 2 | SET DOB = "1990-01-11" 3 | WHERE ID=7; 4 | -------------------------------------------------------------------------------- /Chapter06/Exercise01/Exercise 01 – Creating a Mailing List with a View.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | members.Surname, 3 | members.FirstName, 4 | memberaddress.StreetAddress1, 5 | memberaddress.StreetAddress2, 6 | memberaddress.Town, 7 | memberaddress.Postcode, 8 | states.State 9 | FROM 10 | members 11 | INNER JOIN memberaddress ON memberaddress.MemberID = members.ID 12 | INNER JOIN states ON memberaddress.State = states.ID 13 | WHERE 14 | members.Active <> 0 15 | ORDER BY members.Surname, members.FirstName 16 | -------------------------------------------------------------------------------- /Chapter06/Exercise02/Exercise 4 – Creating a function.sql: -------------------------------------------------------------------------------- 1 | USE autoclub; 2 | 3 | DROP FUNCTION IF EXISTS fn_Lookup; 4 | DELIMITER $$ 5 | CREATE FUNCTION fn_Lookup(LookupKey VARCHAR(50)) RETURNS VARCHAR (200) 6 | DETERMINISTIC 7 | 8 | BEGIN 9 | 10 | DECLARE TheValue VARCHAR(200); 11 | SET TheValue = (SELECT `Value` FROM `lookups` WHERE `Key` = LookupKey); 12 | RETURN (RTRIM(LTRIM(TheValue))); 13 | 14 | END $$ 15 | DELIMITER ; 16 | -------------------------------------------------------------------------------- /Chapter06/Exercise03/Exercise 8 – Creating a Stored Procedure.sql: -------------------------------------------------------------------------------- 1 | USE `autoclub`; 2 | DROP procedure IF EXISTS `sp_ListMembers`; 3 | DELIMITER $$ 4 | 5 | CREATE PROCEDURE `sp_ListMembers` () 6 | 7 | BEGIN 8 | 9 | SELECT * FROM members; 10 | 11 | END$$ 12 | 13 | DELIMITER ; 14 | -------------------------------------------------------------------------------- /Chapter06/Exercise03/Test Script Exercise 8 – Creating a Stored Procedure.sql: -------------------------------------------------------------------------------- 1 | call sp_ListMembers -------------------------------------------------------------------------------- /Chapter06/Exercise04/Exercise 9 – Stored Procedure with parameters.sql: -------------------------------------------------------------------------------- 1 | USE `autoclub`; 2 | DROP procedure IF EXISTS `sp_ListTableData`; 3 | DELIMITER $$ 4 | 5 | CREATE PROCEDURE `sp_ListTableData` (IN TableName VARCHAR(100)) 6 | BEGIN 7 | 8 | SET @sql =CONCAT('SELECT * FROM ',TableName); 9 | PREPARE statement FROM @sql; 10 | EXECUTE statement; 11 | DEALLOCATE PREPARE statement; 12 | 13 | END$$ 14 | 15 | DELIMITER ; 16 | -------------------------------------------------------------------------------- /Chapter06/Exercise04/Test Script Exercise 9 – Stored Procedure with parameters.sql: -------------------------------------------------------------------------------- 1 | call sp_ListTableData("members"); 2 | call sp_ListTableData("memberaddress"); 3 | call sp_ListTableData("identification"); 4 | -------------------------------------------------------------------------------- /Chapter06/Exercise05/Exercise 10 – IN and INOUT.sql: -------------------------------------------------------------------------------- 1 | USE `autoclub`; 2 | DROP procedure IF EXISTS `sp_CountCars_MembersMakes`; 3 | DELIMITER $$ 4 | 5 | -- Create the stored procedure with 3 parameters 6 | -- 1) is the Make of car, ie. Holden, this is an IN parameter 7 | -- 2) is an INOUT called TotalCars, the SQL in the procedure will count the Make and assign it to a variable, the count is then added 8 | -- to the TotalCars value which will then be passed back out, updating the variable that passed the original value in 9 | -- 3) is an INOUT named CarString, The Make and Count will be added to this string on each pass through, same as 2) 10 | CREATE PROCEDURE `sp_CountCars_MembersMakes` (IN CarMake VARCHAR(20), INOUT TotalCars INT, INOUT CarString VARCHAR(255)) 11 | 12 | BEGIN 13 | 14 | -- The SQL to count the make. 15 | -- This is a standard SQL statement except for 16 | -- the COUNT value is inserted into a variable, not a field name 17 | -- and the Filter in the WHERE clause come from the CrMake value passed in as the IN parameter 18 | SELECT 19 | Count(vehicle.Make) INTO @TotalInMake -- The count is put INTO the variable @TotalInMake instead of a field name 20 | FROM 21 | vehicle 22 | INNER JOIN members ON vehicle.MemberID = members.ID 23 | INNER JOIN make ON vehicle.Make = make.ID 24 | INNER JOIN vehiclemodel ON vehicle.Model = vehiclemodel.ID 25 | WHERE 26 | members.Active <> 0 AND 27 | make.Make = CarMake; -- The Carmake is used to filter the records 28 | 29 | -- The car count value in @TotalInMake is added to the CarTotal value passed insert 30 | -- This is then passed back out via the INOUT, updating the value in the calling routine 31 | SET TotalCars = TotalCars + @TotalInMake; 32 | 33 | -- The CarMake and the @TotalInMake values are added to the string passed in 34 | -- This is then passed back out via the INOUT, updating the value in the calling routine 35 | SET CarString = CONCAT(CarString,CarMake,"=",@TotalInMake, " "); 36 | 37 | END$$ 38 | 39 | DELIMITER ; 40 | -------------------------------------------------------------------------------- /Chapter06/Exercise05/Test Script Exercise 10 – IN and INOUT.sql: -------------------------------------------------------------------------------- 1 | -- Declare the variables 2 | SET @TotalCars = 0; -- Declare and initialise @TotalCars 3 | SET @MakeString = "Car Make/Count :- "; -- Declare and initialise @MakeString 4 | 5 | -- Each call will pass in the Make to be counted 6 | -- Each call will pass in the current value for @TotalCars and @MakeString 7 | -- Each call will add to the string or total 8 | call sp_CountCars_MembersMakes("Holden",@TotalCars,@MakeString); 9 | call sp_CountCars_MembersMakes("Ford",@TotalCars,@MakeString); 10 | call sp_CountCars_MembersMakes("Mazda",@TotalCars,@MakeString); 11 | call sp_CountCars_MembersMakes("Toyota",@TotalCars,@MakeString); 12 | 13 | -- Output the make string and total when finish 14 | SELECT @MakeString, @TotalCars 15 | -------------------------------------------------------------------------------- /Chapter06/Exercise06/Check Test Members Age.sql: -------------------------------------------------------------------------------- 1 | SELECT Firstname, Surname, DOB FROM members WHERE ID=2 -------------------------------------------------------------------------------- /Chapter06/Exercise06/Create Business Rule.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO `autoclub`.`lookups` (`Key`, `Value`, `Descriptions`) VALUES ('MinMemberAge','18','Minimum age in years for members'); -------------------------------------------------------------------------------- /Chapter06/Exercise06/Create CheckMemberAge Trigger.sql: -------------------------------------------------------------------------------- 1 | DELIMITER $$ 2 | 3 | DROP TRIGGER IF EXISTS autoclub.CheckMemberAge$$ 4 | USE `autoclub`$$ 5 | CREATE TRIGGER `CheckMemberAge` BEFORE UPDATE ON `members` FOR EACH ROW BEGIN 6 | 7 | declare msg varchar(128); 8 | 9 | SET @MinAge = (SELECT `Value` FROM LOOKUPS WHERE `KEY`='MinMemberAge'); 10 | 11 | if NEW.dob > (SELECT DATE_SUB(curdate(), interval @MinAge year)) THEN 12 | set msg = concat('MyTriggerError: Minimum member age is: ', @MinAge); 13 | signal sqlstate '45000' set message_text = msg; 14 | end if; 15 | 16 | END$$ 17 | DELIMITER ; 18 | -------------------------------------------------------------------------------- /Chapter06/Exercise06/Prepare MyISAM version of members table.sql: -------------------------------------------------------------------------------- 1 | USE `autoclub`; 2 | 3 | -- Copy the members table to members_myisam 4 | DROP TABLE IF EXISTS autoclub.members_myisam; 5 | CREATE TABLE IF NOT EXISTS members_myisam SELECT * FROM 6 | members; 7 | 8 | -- Set the Primary Key field and the Auto Increment properies on ID 9 | ALTER TABLE `autoclub`.`members_myisam` 10 | CHANGE COLUMN `ID` `ID` INT(11) NOT NULL AUTO_INCREMENT , 11 | ADD PRIMARY KEY (`ID`); 12 | 13 | -- Change the tables engine to MyISAM so we can test it 14 | ALTER TABLE `autoclub`.`members_myisam` 15 | ENGINE = MyISAM ; 16 | 17 | -- Create the trigger for members_MyISAM 18 | DELIMITER $$ 19 | DROP TRIGGER IF EXISTS autoclub.CheckMemberAge_MyISAM$$ 20 | USE `autoclub`$$ 21 | CREATE TRIGGER `CheckMemberAge_MyISAM` BEFORE UPDATE ON `members_MyISAM` FOR EACH ROW BEGIN 22 | 23 | declare msg varchar(128); 24 | 25 | SET @MinAge = (SELECT `Value` FROM LOOKUPS WHERE `KEY`='MinMemberAge'); 26 | 27 | if NEW.dob > (SELECT DATE_SUB(curdate(), interval @MinAge year)) THEN 28 | set msg = concat('MyTriggerError: Minimum member age is: ', @MinAge); 29 | signal sqlstate '45000' set message_text = msg; 30 | end if; 31 | 32 | END$$ 33 | 34 | 35 | 36 | DROP TRIGGER IF EXISTS autoclub.LogMemberChanges_myisam$$ 37 | CREATE TRIGGER `LogMemberChanges_myisam` AFTER UPDATE ON `members_myisam` FOR EACH ROW BEGIN 38 | 39 | 40 | if NEW.Surname <> OLD.Surname THEN 41 | INSERT INTO `logging_database`.`changelog` (`Database`, `TableName`, `PKValue`, `OldValue`, `NewValue`) 42 | VALUES ('autoclub', 'Members_MyISAM',OLD.ID, OLD.Surname,NEW.Surname); 43 | end if; 44 | 45 | if NEW.MiddleNames <> OLD.MiddleNames THEN 46 | INSERT INTO `logging_database`.`changelog` (`Database`, `TableName`, `PKValue`, `OldValue`, `NewValue`) 47 | VALUES ('autoclub', 'Members_MyISAM',OLD.ID, OLD.MiddleNames,NEW.MiddleNames); 48 | end if; 49 | 50 | if NEW.FirstName <> OLD.FirstName THEN 51 | INSERT INTO `logging_database`.`changelog` (`Database`, `TableName`, `PKValue`, `OldValue`, `NewValue`) 52 | VALUES ('autoclub', 'Members_MyISAM',OLD.ID, OLD.FirstName,NEW.FirstName); 53 | end if; 54 | 55 | if NEW.DOB <> OLD.DOB THEN 56 | INSERT INTO `logging_database`.`changelog` (`Database`, `TableName`, `PKValue`, `OldValue`, `NewValue`) 57 | VALUES ('autoclub', 'Members_MyISAM',OLD.ID, OLD.DOB ,NEW.DOB ); 58 | end if; 59 | 60 | if NEW.PhotoPath <> OLD.PhotoPath THEN 61 | INSERT INTO `logging_database`.`changelog` (`Database`, `TableName`, `PKValue`, `OldValue`, `NewValue`) 62 | VALUES ('autoclub', 'Members_MyISAM',OLD.ID, OLD.PhotoPath,NEW.PhotoPath); 63 | end if; 64 | 65 | if NEW.SigPath <> OLD.SigPath THEN 66 | INSERT INTO `logging_database`.`changelog` (`Database`, `TableName`, `PKValue`, `OldValue`, `NewValue`) 67 | VALUES ('autoclub', 'Members_MyISAM',OLD.ID, OLD.SigPath,NEW.SigPath); 68 | end if; 69 | 70 | if NEW.Active <> OLD.Active THEN 71 | INSERT INTO `logging_database`.`changelog` (`Database`, `TableName`, `PKValue`, `OldValue`, `NewValue`) 72 | VALUES ('autoclub', 'Members_MyISAM',OLD.ID, OLD.Active,NEW.Active); 73 | end if; 74 | 75 | if NEW.JoinDate <> OLD.JoinDate THEN 76 | INSERT INTO `logging_database`.`changelog` (`Database`, `TableName`, `PKValue`, `OldValue`, `NewValue`) 77 | VALUES ('autoclub', 'Members_MyISAM',OLD.ID, OLD.JoinDate,NEW.JoinDate); 78 | end if; 79 | 80 | if NEW.InactiveDate <> OLD.InactiveDate THEN 81 | INSERT INTO `logging_database`.`changelog` (`Database`, `TableName`, `PKValue`, `OldValue`, `NewValue`) 82 | VALUES ('autoclub', 'Members_MyISAM',OLD.ID, OLD.InactiveDate,NEW.InactiveDate); 83 | end if; 84 | 85 | END $$ 86 | DELIMITER ; 87 | 88 | -------------------------------------------------------------------------------- /Chapter06/Exercise06/Test - Fail - CheckMemberAge.sql: -------------------------------------------------------------------------------- 1 | update `autoclub`.`members` SET `DOB` = '2006-10-15' WHERE ID = 2; -------------------------------------------------------------------------------- /Chapter06/Exercise06/Test - Success - CheckMemberAge.sql: -------------------------------------------------------------------------------- 1 | update `autoclub`.`members` SET `DOB` = '2000-10-15' WHERE ID = 2; -------------------------------------------------------------------------------- /Chapter06/Exercise07/ch6_Excercise_7_01.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE test; 2 | 3 | use test; 4 | 5 | CREATE TABLE animals ( id int primary key, name varchar(255) ); 6 | 7 | DESCRIBE animals; 8 | 9 | INSERT INTO animals VALUES(1, 'dog'); 10 | 11 | SELECT * FROM animals; 12 | 13 | ROLLBACK; 14 | 15 | SELECT * FROM animals; 16 | -------------------------------------------------------------------------------- /Chapter07/Activity7.01/Activity_5_01_Solution_Create_Database.js: -------------------------------------------------------------------------------- 1 | //Verified 2 | var mysqlconnection = require("./mysqlconnection.js"); 3 | 4 | mysqlconnection.query("CREATE DATABASE `MOTdatabase`", 5 | function (err) { 6 | if (err) throw "Problem creating the database:- " + 7 | err.code; 8 | console.log("Database created"); 9 | process.exit(); 10 | }); 11 | -------------------------------------------------------------------------------- /Chapter07/Activity7.01/Activity_5_01_Solution_Create_Tables.js: -------------------------------------------------------------------------------- 1 | //Verified 2 | 3 | var mysqlconnection = require("./mysqlconnection.js"); 4 | var sql = "CREATE TABLE `MOTdatabase`.`Customers` ( \ 5 | `CustID` int(11) NOT NULL AUTO_INCREMENT, \ 6 | `CustomerName` varchar(50) NOT NULL, \ 7 | PRIMARY KEY (`CustID`)\ 8 | );" 9 | 10 | mysqlconnection.query(sql, function (err) { 11 | if (err) throw "Problem creating the Table:- " + err.code; 12 | console.log("Table created"); 13 | }); 14 | 15 | var sql = "CREATE TABLE `MOTdatabase`.`CustomerPurchases` (\ 16 | `CPID` int(11) NOT NULL AUTO_INCREMENT, \ 17 | `CustID` int(11) NOT NULL, \ 18 | `SKU` varchar(20) NOT NULL, \ 19 | `SaleDateTime` varchar(25) NOT NULL, \ 20 | `Quantity` int(11) NOT NULL, \ 21 | PRIMARY KEY (`CPID`) \ 22 | );" 23 | 24 | mysqlconnection.query(sql, function (err) { 25 | if (err) throw "Problem creating the Table:- " + err.code; 26 | console.log("Table created"); 27 | process.exit(); 28 | }); 29 | -------------------------------------------------------------------------------- /Chapter07/Activity7.01/Requirements.txt: -------------------------------------------------------------------------------- 1 | Requirements 2 | Database name:- MOTdatabase 3 | Table Name:- Customers 4 | Table Definition:- 5 | -CUSTID, Int, Primary Key 6 | -CustName, VarChar(50), NOT NULL 7 | Table Name:- CustomerPurchases 8 | Table Definition:- 9 | CPID, Int, Primary Key 10 | CustID, Int, NOT NULL 11 | SKU, VarChar(20), NOT NULL 12 | SaleDateTime, VarChar(25), NOT NULL 13 | Quantity, Int, NOT NULL -------------------------------------------------------------------------------- /Chapter07/Activity7.01/mysqlconnection.js: -------------------------------------------------------------------------------- 1 | //This is the final incarnation of the mysqlconnection script 2 | //it is now a module that can be reused. 3 | //By setting this connection script up as a module, you only need to 4 | //put the connection details in here and NOT in other scripts 5 | //If the details change in the future, you only need to change them here, once, all other scripts 6 | //using the module will still connect, so much easier for maintenance 7 | 8 | 9 | //Include the sql2 module so we can connect to the database server 10 | var mysql = require('mysql2'); 11 | 12 | //Create the connection 13 | var mysqlconnection = mysql.createConnection({ 14 | host: "localhost", 15 | port: "3306", //This will usually be 3306 but can be changed on the server or if the server is on the internet 16 | user: "root", 17 | password: "" 18 | }); 19 | 20 | 21 | //Start the Connection Block 22 | //Make the connection, include error checking 23 | mysqlconnection.connect(function(err) { 24 | 25 | //Test for an error and provide a suitable message and the code if one occurs 26 | if (err) throw "mysqlconnection.js problem connecting to MySQL, the ERROR CODE is :-" + err.code; 27 | 28 | //No error so report to the console that connection was successful 29 | //This can be omitted 30 | console.log("Connected to MySQL!"); 31 | 32 | 33 | //Close off the connection blocks bracketing 34 | }); 35 | 36 | //End the Connection Block 37 | 38 | //This is the magic line, it allows the object mysqlconnection to be exported 39 | //which means other scripts can .require(myqlconnection) and use the connection...so cool 40 | module.exports = mysqlconnection; 41 | 42 | //No requirement for a process.exit in this script -------------------------------------------------------------------------------- /Chapter07/Databases/GP_PracticeDatabase.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE IF NOT EXISTS `backuppractice` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */ /*!80016 DEFAULT ENCRYPTION='N' */; 2 | USE `backuppractice`; 3 | -- MySQL dump 10.13 Distrib 5.7.12, for Win32 (AMD64) 4 | -- 5 | -- Host: 192.168.0.3 Database: backuppractice 6 | -- ------------------------------------------------------ 7 | -- Server version 8.0.17 8 | 9 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 10 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 11 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 12 | /*!40101 SET NAMES utf8mb4 */; 13 | /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; 14 | /*!40103 SET TIME_ZONE='+00:00' */; 15 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 16 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 17 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 18 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 19 | 20 | -- 21 | -- Table structure for table `continents` 22 | -- 23 | 24 | DROP TABLE IF EXISTS `continents`; 25 | /*!40101 SET @saved_cs_client = @@character_set_client */; 26 | /*!40101 SET character_set_client = utf8mb4 */; 27 | CREATE TABLE `continents` ( 28 | `ContinentID` int(11) NOT NULL AUTO_INCREMENT, 29 | `Continent` varchar(13) DEFAULT NULL, 30 | PRIMARY KEY (`ContinentID`) 31 | ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 32 | /*!40101 SET character_set_client = @saved_cs_client */; 33 | 34 | -- 35 | -- Dumping data for table `continents` 36 | -- 37 | 38 | LOCK TABLES `continents` WRITE; 39 | /*!40000 ALTER TABLE `continents` DISABLE KEYS */; 40 | INSERT INTO `continents` VALUES (1,'Africa'),(2,'Asia'),(3,'Europe'),(4,'North America'),(5,'Oceania'),(6,'South America'); 41 | /*!40000 ALTER TABLE `continents` ENABLE KEYS */; 42 | UNLOCK TABLES; 43 | 44 | -- 45 | -- Table structure for table `country` 46 | -- 47 | 48 | DROP TABLE IF EXISTS `country`; 49 | /*!40101 SET @saved_cs_client = @@character_set_client */; 50 | /*!40101 SET character_set_client = utf8mb4 */; 51 | CREATE TABLE `country` ( 52 | `CountryID` int(11) NOT NULL AUTO_INCREMENT, 53 | `Country Code` varchar(5) DEFAULT NULL, 54 | `Country Name` varchar(50) DEFAULT NULL, 55 | `ContinentID` int(11) DEFAULT NULL, 56 | PRIMARY KEY (`CountryID`) 57 | ) ENGINE=InnoDB AUTO_INCREMENT=264 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 58 | /*!40101 SET character_set_client = @saved_cs_client */; 59 | 60 | -- 61 | -- Dumping data for table `country` 62 | -- 63 | 64 | LOCK TABLES `country` WRITE; 65 | /*!40000 ALTER TABLE `country` DISABLE KEYS */; 66 | INSERT INTO `country` VALUES (1,'ABW','Aruba',4),(2,'AFG','Afghanistan',2),(3,'AGO','Angola',1),(4,'ALB','Albania',3),(5,'AND','Andorra',3),(6,'ARB','Arab World',NULL),(7,'ARE','United Arab Emirates',2),(8,'ARG','Argentina',6),(9,'ARM','Armenia',2),(10,'ASM','American Samoa',5),(11,'ATG','Antigua and Barbuda',4),(12,'AUS','Australia',5),(13,'AUT','Austria',3),(14,'AZE','Azerbaijan',2),(15,'BDI','Burundi',1),(16,'BEL','Belgium',3),(17,'BEN','Benin',1),(18,'BFA','Burkina Faso',1),(19,'BGD','Bangladesh',2),(20,'BGR','Bulgaria',3),(21,'BHR','Bahrain',2),(22,'BHS','Bahamas, The',4),(23,'BIH','Bosnia and Herzegovina',3),(24,'BLR','Belarus',3),(25,'BLZ','Belize',4),(26,'BMU','Bermuda',4),(27,'BOL','Bolivia',6),(28,'BRA','Brazil',6),(29,'BRB','Barbados',4),(30,'BRN','Brunei Darussalam',2),(31,'BTN','Bhutan',2),(32,'BWA','Botswana',1),(33,'CAF','Central African Republic',1),(34,'CAN','Canada',4),(35,'CEB','Central Europe and the Baltics',NULL),(36,'CHE','Switzerland',3),(37,'CHI','Channel Islands',NULL),(38,'CHL','Chile',6),(39,'CHN','China',2),(40,'CIV','Cote d\'Ivoire',1),(41,'CMR','Cameroon',1),(42,'COD','Congo, Dem. Rep.',1),(43,'COG','Congo, Rep.',1),(44,'COL','Colombia',6),(45,'COM','Comoros',1),(46,'CPV','Cabo Verde',1),(47,'CRI','Costa Rica',4),(48,'CSS','Caribbean small states',NULL),(49,'CUB','Cuba',4),(50,'CUW','Curacao',NULL),(51,'CYM','Cayman Islands',4),(52,'CYP','Cyprus',2),(53,'CZE','Czech Republic',3),(54,'DEU','Germany',3),(55,'DJI','Djibouti',1),(56,'DMA','Dominica',4),(57,'DNK','Denmark',3),(58,'DOM','Dominican Republic',4),(59,'DZA','Algeria',1),(60,'EAP','East Asia & Pacific (excluding high income)',NULL),(61,'EAR','Early-demographic dividend',NULL),(62,'EAS','East Asia & Pacific',NULL),(63,'ECA','Europe & Central Asia (excluding high income)',NULL),(64,'ECS','Europe & Central Asia',NULL),(65,'ECU','Ecuador',6),(66,'EGY','Egypt, Arab Rep.',1),(67,'EMU','Euro area',NULL),(68,'ERI','Eritrea',1),(69,'ESP','Spain',3),(70,'EST','Estonia',3),(71,'ETH','Ethiopia',1),(72,'EUU','European Union',NULL),(73,'FCS','Fragile and conflict affected situations',NULL),(74,'FIN','Finland',3),(75,'FJI','Fiji',5),(76,'FRA','France',3),(77,'FRO','Faroe Islands',3),(78,'FSM','Micronesia, Fed. Sts.',5),(79,'GAB','Gabon',1),(80,'GBR','United Kingdom',3),(81,'GEO','Georgia',2),(82,'GHA','Ghana',1),(83,'GIB','Gibraltar',3),(84,'GIN','Guinea',1),(85,'GMB','Gambia, The',1),(86,'GNB','Guinea-Bissau',1),(87,'GNQ','Equatorial Guinea',1),(88,'GRC','Greece',3),(89,'GRD','Grenada',4),(90,'GRL','Greenland',4),(91,'GTM','Guatemala',4),(92,'GUM','Guam',5),(93,'GUY','Guyana',6),(94,'HIC','High income',NULL),(95,'HKG','Hong Kong SAR, China',2),(96,'HND','Honduras',4),(97,'HPC','Heavily indebted poor countries (HIPC)',NULL),(98,'HRV','Croatia',3),(99,'HTI','Haiti',4),(100,'HUN','Hungary',3),(101,'IBD','IBRD only',NULL),(102,'IBT','IDA & IBRD total',NULL),(103,'IDA','IDA total',NULL),(104,'IDB','IDA blend',NULL),(105,'IDN','Indonesia',2),(106,'IDX','IDA only',NULL),(107,'IMN','Isle of Man',NULL),(108,'IND','India',2),(109,'IRL','Ireland',3),(110,'IRN','Iran, Islamic Rep.',2),(111,'IRQ','Iraq',2),(112,'ISL','Iceland',3),(113,'ISR','Israel',2),(114,'ITA','Italy',3),(115,'JAM','Jamaica',4),(116,'JOR','Jordan',2),(117,'JPN','Japan',2),(118,'KAZ','Kazakhstan',2),(119,'KEN','Kenya',1),(120,'KGZ','Kyrgyz Republic',2),(121,'KHM','Cambodia',2),(122,'KIR','Kiribati',5),(123,'KNA','St. Kitts and Nevis',4),(124,'KOR','Korea, Rep.',2),(125,'KWT','Kuwait',2),(126,'LAC','Latin America & Caribbean (excluding high income)',NULL),(127,'LAO','Lao PDR',2),(128,'LBN','Lebanon',2),(129,'LBR','Liberia',1),(130,'LBY','Libya',1),(131,'LCA','St. Lucia',4),(132,'LCN','Latin America & Caribbean',NULL),(133,'LDC','Least developed countries: UN classification',NULL),(134,'LIC','Low income',NULL),(135,'LIE','Liechtenstein',3),(136,'LKA','Sri Lanka',2),(137,'LMC','Lower middle income',NULL),(138,'LMY','Low & middle income',NULL),(139,'LSO','Lesotho',1),(140,'LTE','Late-demographic dividend',NULL),(141,'LTU','Lithuania',3),(142,'LUX','Luxembourg',3),(143,'LVA','Latvia',3),(144,'MAC','Macao SAR, China',2),(145,'MAF','St. Martin (French part)',NULL),(146,'MAR','Morocco',1),(147,'MCO','Monaco',3),(148,'MDA','Moldova',3),(149,'MDG','Madagascar',1),(150,'MDV','Maldives',2),(151,'MEA','Middle East & North Africa',NULL),(152,'MEX','Mexico',4),(153,'MHL','Marshall Islands',5),(154,'MIC','Middle income',NULL),(155,'MKD','Macedonia, FYR',3),(156,'MLI','Mali',1),(157,'MLT','Malta',3),(158,'MMR','Myanmar',2),(159,'MNA','Middle East & North Africa (excluding high income)',NULL),(160,'MNE','Montenegro',NULL),(161,'MNG','Mongolia',2),(162,'MNP','Northern Mariana Islands',5),(163,'MOZ','Mozambique',1),(164,'MRT','Mauritania',1),(165,'MUS','Mauritius',1),(166,'MWI','Malawi',1),(167,'MYS','Malaysia',2),(168,'NAC','North America',NULL),(169,'NAM','Namibia',1),(170,'NCL','New Caledonia',5),(171,'NER','Niger',1),(172,'NGA','Nigeria',1),(173,'NIC','Nicaragua',4),(174,'NLD','Netherlands',3),(175,'NOR','Norway',3),(176,'NPL','Nepal',2),(177,'NRU','Nauru',5),(178,'NZL','New Zealand',5),(179,'OED','OECD members',NULL),(180,'OMN','Oman',2),(181,'OSS','Other small states',NULL),(182,'PAK','Pakistan',2),(183,'PAN','Panama',4),(184,'PER','Peru',6),(185,'PHL','Philippines',2),(186,'PLW','Palau',5),(187,'PNG','Papua New Guinea',5),(188,'POL','Poland',3),(189,'PRE','Pre-demographic dividend',NULL),(190,'PRI','Puerto Rico',4),(191,'PRK','Korea, Dem. People\'s Rep.',2),(192,'PRT','Portugal',3),(193,'PRY','Paraguay',6),(194,'PSE','West Bank and Gaza',2),(195,'PSS','Pacific island small states',NULL),(196,'PST','Post-demographic dividend',NULL),(197,'PYF','French Polynesia',5),(198,'QAT','Qatar',2),(199,'ROU','Romania',NULL),(200,'RUS','Russian Federation',3),(201,'RWA','Rwanda',1),(202,'SAS','South Asia',NULL),(203,'SAU','Saudi Arabia',2),(204,'SDN','Sudan',1),(205,'SEN','Senegal',1),(206,'SGP','Singapore',2),(207,'SLB','Solomon Islands',5),(208,'SLE','Sierra Leone',1),(209,'SLV','El Salvador',4),(210,'SMR','San Marino',3),(211,'SOM','Somalia',1),(212,'SRB','Serbia',NULL),(213,'SSA','Sub-Saharan Africa (excluding high income)',NULL),(214,'SSD','South Sudan',NULL),(215,'SSF','Sub-Saharan Africa',NULL),(216,'SST','Small states',NULL),(217,'STP','Sao Tome and Principe',1),(218,'SUR','Suriname',6),(219,'SVK','Slovak Republic',3),(220,'SVN','Slovenia',3),(221,'SWE','Sweden',3),(222,'SWZ','Eswatini',1),(223,'SXM','Sint Maarten (Dutch part)',NULL),(224,'SYC','Seychelles',1),(225,'SYR','Syrian Arab Republic',2),(226,'TCA','Turks and Caicos Islands',4),(227,'TCD','Chad',1),(228,'TEA','East Asia & Pacific (IDA & IBRD)',NULL),(229,'TEC','Europe & Central Asia (IDA & IBRD)',NULL),(230,'TGO','Togo',1),(231,'THA','Thailand',2),(232,'TJK','Tajikistan',2),(233,'TKM','Turkmenistan',2),(234,'TLA','Latin America & Caribbean (IDA & IBRD)',NULL),(235,'TLS','Timor-Leste',NULL),(236,'TMN','Middle East & North Africa (IDA & IBRD)',NULL),(237,'TON','Tonga',5),(238,'TSA','South Asia (IDA & IBRD)',NULL),(239,'TSS','Sub-Saharan Africa (IDA & IBRD)',NULL),(240,'TTO','Trinidad and Tobago',4),(241,'TUN','Tunisia',1),(242,'TUR','Turkey',2),(243,'TUV','Tuvalu',5),(244,'TZA','Tanzania',1),(245,'UGA','Uganda',1),(246,'UKR','Ukraine',3),(247,'UMC','Upper middle income',NULL),(248,'URY','Uruguay',6),(249,'USA','United States',4),(250,'UZB','Uzbekistan',2),(251,'VCT','St. Vincent and the Grenadines',4),(252,'VEN','Venezuela, RB',6),(253,'VGB','British Virgin Islands',4),(254,'VIR','Virgin Islands (U.S.)',4),(255,'VNM','Vietnam',2),(256,'VUT','Vanuatu',5),(257,'WLD','World',NULL),(258,'WSM','Samoa',5),(259,'XKX','Kosovo',NULL),(260,'YEM','Yemen, Rep.',2),(261,'ZAF','South Africa',1),(262,'ZMB','Zambia',1),(263,'ZWE','Zimbabwe',1); 67 | /*!40000 ALTER TABLE `country` ENABLE KEYS */; 68 | UNLOCK TABLES; 69 | /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; 70 | 71 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 72 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 73 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 74 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 75 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 76 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 77 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 78 | 79 | -- Dump completed on 2019-09-26 18:21:26 80 | -------------------------------------------------------------------------------- /Chapter07/Databases/PracticeDatabase 20190926a.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE IF NOT EXISTS `backuppractice` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */ /*!80016 DEFAULT ENCRYPTION='N' */; 2 | USE `backuppractice`; 3 | -- MySQL dump 10.13 Distrib 5.7.12, for Win32 (AMD64) 4 | -- 5 | -- Host: 192.168.0.3 Database: backuppractice 6 | -- ------------------------------------------------------ 7 | -- Server version 8.0.17 8 | 9 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 10 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 11 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 12 | /*!40101 SET NAMES utf8mb4 */; 13 | /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; 14 | /*!40103 SET TIME_ZONE='+00:00' */; 15 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 16 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 17 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 18 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 19 | 20 | -- 21 | -- Table structure for table `continents` 22 | -- 23 | 24 | DROP TABLE IF EXISTS `continents`; 25 | /*!40101 SET @saved_cs_client = @@character_set_client */; 26 | /*!40101 SET character_set_client = utf8mb4 */; 27 | CREATE TABLE `continents` ( 28 | `ContinentID` int(11) NOT NULL AUTO_INCREMENT, 29 | `Continent` varchar(13) DEFAULT NULL, 30 | PRIMARY KEY (`ContinentID`) 31 | ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 32 | /*!40101 SET character_set_client = @saved_cs_client */; 33 | 34 | -- 35 | -- Dumping data for table `continents` 36 | -- 37 | 38 | LOCK TABLES `continents` WRITE; 39 | /*!40000 ALTER TABLE `continents` DISABLE KEYS */; 40 | INSERT INTO `continents` VALUES (1,'Africa'),(2,'Asia'),(3,'Europe'),(4,'North America'),(5,'Oceania'),(6,'South America'); 41 | /*!40000 ALTER TABLE `continents` ENABLE KEYS */; 42 | UNLOCK TABLES; 43 | 44 | -- 45 | -- Table structure for table `country` 46 | -- 47 | 48 | DROP TABLE IF EXISTS `country`; 49 | /*!40101 SET @saved_cs_client = @@character_set_client */; 50 | /*!40101 SET character_set_client = utf8mb4 */; 51 | CREATE TABLE `country` ( 52 | `CountryID` int(11) NOT NULL AUTO_INCREMENT, 53 | `Country Code` varchar(5) DEFAULT NULL, 54 | `Country Name` varchar(50) DEFAULT NULL, 55 | `ContinentID` int(11) DEFAULT NULL, 56 | PRIMARY KEY (`CountryID`) 57 | ) ENGINE=InnoDB AUTO_INCREMENT=264 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 58 | /*!40101 SET character_set_client = @saved_cs_client */; 59 | 60 | -- 61 | -- Dumping data for table `country` 62 | -- 63 | 64 | LOCK TABLES `country` WRITE; 65 | /*!40000 ALTER TABLE `country` DISABLE KEYS */; 66 | INSERT INTO `country` VALUES (1,'ABW','Aruba',4),(2,'AFG','Afghanistan',2),(3,'AGO','Angola',1),(4,'ALB','Albania',3),(5,'AND','Andorra',3),(6,'ARB','Arab World',NULL),(7,'ARE','United Arab Emirates',2),(8,'ARG','Argentina',6),(9,'ARM','Armenia',2),(10,'ASM','American Samoa',5),(11,'ATG','Antigua and Barbuda',4),(12,'AUS','Australia',5),(13,'AUT','Austria',3),(14,'AZE','Azerbaijan',2),(15,'BDI','Burundi',1),(16,'BEL','Belgium',3),(17,'BEN','Benin',1),(18,'BFA','Burkina Faso',1),(19,'BGD','Bangladesh',2),(20,'BGR','Bulgaria',3),(21,'BHR','Bahrain',2),(22,'BHS','Bahamas, The',4),(23,'BIH','Bosnia and Herzegovina',3),(24,'BLR','Belarus',3),(25,'BLZ','Belize',4),(26,'BMU','Bermuda',4),(27,'BOL','Bolivia',6),(28,'BRA','Brazil',6),(29,'BRB','Barbados',4),(30,'BRN','Brunei Darussalam',2),(31,'BTN','Bhutan',2),(32,'BWA','Botswana',1),(33,'CAF','Central African Republic',1),(34,'CAN','Canada',4),(35,'CEB','Central Europe and the Baltics',NULL),(36,'CHE','Switzerland',3),(37,'CHI','Channel Islands',NULL),(38,'CHL','Chile',6),(39,'CHN','China',2),(40,'CIV','Cote d\'Ivoire',1),(41,'CMR','Cameroon',1),(42,'COD','Congo, Dem. Rep.',1),(43,'COG','Congo, Rep.',1),(44,'COL','Colombia',6),(45,'COM','Comoros',1),(46,'CPV','Cabo Verde',1),(47,'CRI','Costa Rica',4),(48,'CSS','Caribbean small states',NULL),(49,'CUB','Cuba',4),(50,'CUW','Curacao',NULL),(51,'CYM','Cayman Islands',4),(52,'CYP','Cyprus',2),(53,'CZE','Czech Republic',3),(54,'DEU','Germany',3),(55,'DJI','Djibouti',1),(56,'DMA','Dominica',4),(57,'DNK','Denmark',3),(58,'DOM','Dominican Republic',4),(59,'DZA','Algeria',1),(60,'EAP','East Asia & Pacific (excluding high income)',NULL),(61,'EAR','Early-demographic dividend',NULL),(62,'EAS','East Asia & Pacific',NULL),(63,'ECA','Europe & Central Asia (excluding high income)',NULL),(64,'ECS','Europe & Central Asia',NULL),(65,'ECU','Ecuador',6),(66,'EGY','Egypt, Arab Rep.',1),(67,'EMU','Euro area',NULL),(68,'ERI','Eritrea',1),(69,'ESP','Spain',3),(70,'EST','Estonia',3),(71,'ETH','Ethiopia',1),(72,'EUU','European Union',NULL),(73,'FCS','Fragile and conflict affected situations',NULL),(74,'FIN','Finland',3),(75,'FJI','Fiji',5),(76,'FRA','France',3),(77,'FRO','Faroe Islands',3),(78,'FSM','Micronesia, Fed. Sts.',5),(79,'GAB','Gabon',1),(80,'GBR','United Kingdom',3),(81,'GEO','Georgia',2),(82,'GHA','Ghana',1),(83,'GIB','Gibraltar',3),(84,'GIN','Guinea',1),(85,'GMB','Gambia, The',1),(86,'GNB','Guinea-Bissau',1),(87,'GNQ','Equatorial Guinea',1),(88,'GRC','Greece',3),(89,'GRD','Grenada',4),(90,'GRL','Greenland',4),(91,'GTM','Guatemala',4),(92,'GUM','Guam',5),(93,'GUY','Guyana',6),(94,'HIC','High income',NULL),(95,'HKG','Hong Kong SAR, China',2),(96,'HND','Honduras',4),(97,'HPC','Heavily indebted poor countries (HIPC)',NULL),(98,'HRV','Croatia',3),(99,'HTI','Haiti',4),(100,'HUN','Hungary',3),(101,'IBD','IBRD only',NULL),(102,'IBT','IDA & IBRD total',NULL),(103,'IDA','IDA total',NULL),(104,'IDB','IDA blend',NULL),(105,'IDN','Indonesia',2),(106,'IDX','IDA only',NULL),(107,'IMN','Isle of Man',NULL),(108,'IND','India',2),(109,'IRL','Ireland',3),(110,'IRN','Iran, Islamic Rep.',2),(111,'IRQ','Iraq',2),(112,'ISL','Iceland',3),(113,'ISR','Israel',2),(114,'ITA','Italy',3),(115,'JAM','Jamaica',4),(116,'JOR','Jordan',2),(117,'JPN','Japan',2),(118,'KAZ','Kazakhstan',2),(119,'KEN','Kenya',1),(120,'KGZ','Kyrgyz Republic',2),(121,'KHM','Cambodia',2),(122,'KIR','Kiribati',5),(123,'KNA','St. Kitts and Nevis',4),(124,'KOR','Korea, Rep.',2),(125,'KWT','Kuwait',2),(126,'LAC','Latin America & Caribbean (excluding high income)',NULL),(127,'LAO','Lao PDR',2),(128,'LBN','Lebanon',2),(129,'LBR','Liberia',1),(130,'LBY','Libya',1),(131,'LCA','St. Lucia',4),(132,'LCN','Latin America & Caribbean',NULL),(133,'LDC','Least developed countries: UN classification',NULL),(134,'LIC','Low income',NULL),(135,'LIE','Liechtenstein',3),(136,'LKA','Sri Lanka',2),(137,'LMC','Lower middle income',NULL),(138,'LMY','Low & middle income',NULL),(139,'LSO','Lesotho',1),(140,'LTE','Late-demographic dividend',NULL),(141,'LTU','Lithuania',3),(142,'LUX','Luxembourg',3),(143,'LVA','Latvia',3),(144,'MAC','Macao SAR, China',2),(145,'MAF','St. Martin (French part)',NULL),(146,'MAR','Morocco',1),(147,'MCO','Monaco',3),(148,'MDA','Moldova',3),(149,'MDG','Madagascar',1),(150,'MDV','Maldives',2),(151,'MEA','Middle East & North Africa',NULL),(152,'MEX','Mexico',4),(153,'MHL','Marshall Islands',5),(154,'MIC','Middle income',NULL),(155,'MKD','Macedonia, FYR',3),(156,'MLI','Mali',1),(157,'MLT','Malta',3),(158,'MMR','Myanmar',2),(159,'MNA','Middle East & North Africa (excluding high income)',NULL),(160,'MNE','Montenegro',NULL),(161,'MNG','Mongolia',2),(162,'MNP','Northern Mariana Islands',5),(163,'MOZ','Mozambique',1),(164,'MRT','Mauritania',1),(165,'MUS','Mauritius',1),(166,'MWI','Malawi',1),(167,'MYS','Malaysia',2),(168,'NAC','North America',NULL),(169,'NAM','Namibia',1),(170,'NCL','New Caledonia',5),(171,'NER','Niger',1),(172,'NGA','Nigeria',1),(173,'NIC','Nicaragua',4),(174,'NLD','Netherlands',3),(175,'NOR','Norway',3),(176,'NPL','Nepal',2),(177,'NRU','Nauru',5),(178,'NZL','New Zealand',5),(179,'OED','OECD members',NULL),(180,'OMN','Oman',2),(181,'OSS','Other small states',NULL),(182,'PAK','Pakistan',2),(183,'PAN','Panama',4),(184,'PER','Peru',6),(185,'PHL','Philippines',2),(186,'PLW','Palau',5),(187,'PNG','Papua New Guinea',5),(188,'POL','Poland',3),(189,'PRE','Pre-demographic dividend',NULL),(190,'PRI','Puerto Rico',4),(191,'PRK','Korea, Dem. People\'s Rep.',2),(192,'PRT','Portugal',3),(193,'PRY','Paraguay',6),(194,'PSE','West Bank and Gaza',2),(195,'PSS','Pacific island small states',NULL),(196,'PST','Post-demographic dividend',NULL),(197,'PYF','French Polynesia',5),(198,'QAT','Qatar',2),(199,'ROU','Romania',NULL),(200,'RUS','Russian Federation',3),(201,'RWA','Rwanda',1),(202,'SAS','South Asia',NULL),(203,'SAU','Saudi Arabia',2),(204,'SDN','Sudan',1),(205,'SEN','Senegal',1),(206,'SGP','Singapore',2),(207,'SLB','Solomon Islands',5),(208,'SLE','Sierra Leone',1),(209,'SLV','El Salvador',4),(210,'SMR','San Marino',3),(211,'SOM','Somalia',1),(212,'SRB','Serbia',NULL),(213,'SSA','Sub-Saharan Africa (excluding high income)',NULL),(214,'SSD','South Sudan',NULL),(215,'SSF','Sub-Saharan Africa',NULL),(216,'SST','Small states',NULL),(217,'STP','Sao Tome and Principe',1),(218,'SUR','Suriname',6),(219,'SVK','Slovak Republic',3),(220,'SVN','Slovenia',3),(221,'SWE','Sweden',3),(222,'SWZ','Eswatini',1),(223,'SXM','Sint Maarten (Dutch part)',NULL),(224,'SYC','Seychelles',1),(225,'SYR','Syrian Arab Republic',2),(226,'TCA','Turks and Caicos Islands',4),(227,'TCD','Chad',1),(228,'TEA','East Asia & Pacific (IDA & IBRD)',NULL),(229,'TEC','Europe & Central Asia (IDA & IBRD)',NULL),(230,'TGO','Togo',1),(231,'THA','Thailand',2),(232,'TJK','Tajikistan',2),(233,'TKM','Turkmenistan',2),(234,'TLA','Latin America & Caribbean (IDA & IBRD)',NULL),(235,'TLS','Timor-Leste',NULL),(236,'TMN','Middle East & North Africa (IDA & IBRD)',NULL),(237,'TON','Tonga',5),(238,'TSA','South Asia (IDA & IBRD)',NULL),(239,'TSS','Sub-Saharan Africa (IDA & IBRD)',NULL),(240,'TTO','Trinidad and Tobago',4),(241,'TUN','Tunisia',1),(242,'TUR','Turkey',2),(243,'TUV','Tuvalu',5),(244,'TZA','Tanzania',1),(245,'UGA','Uganda',1),(246,'UKR','Ukraine',3),(247,'UMC','Upper middle income',NULL),(248,'URY','Uruguay',6),(249,'USA','United States',4),(250,'UZB','Uzbekistan',2),(251,'VCT','St. Vincent and the Grenadines',4),(252,'VEN','Venezuela, RB',6),(253,'VGB','British Virgin Islands',4),(254,'VIR','Virgin Islands (U.S.)',4),(255,'VNM','Vietnam',2),(256,'VUT','Vanuatu',5),(257,'WLD','World',NULL),(258,'WSM','Samoa',5),(259,'XKX','Kosovo',NULL),(260,'YEM','Yemen, Rep.',2),(261,'ZAF','South Africa',1),(262,'ZMB','Zambia',1),(263,'ZWE','Zimbabwe',1); 67 | /*!40000 ALTER TABLE `country` ENABLE KEYS */; 68 | UNLOCK TABLES; 69 | /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; 70 | 71 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 72 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 73 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 74 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 75 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 76 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 77 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 78 | 79 | -- Dump completed on 2019-09-26 20:06:35 80 | -------------------------------------------------------------------------------- /Chapter07/Databases/PracticeDatabaseNoSchema 20190926a.sql: -------------------------------------------------------------------------------- 1 | -- MySQL dump 10.13 Distrib 5.7.12, for Win32 (AMD64) 2 | -- 3 | -- Host: 192.168.0.3 Database: backuppractice 4 | -- ------------------------------------------------------ 5 | -- Server version 8.0.17 6 | 7 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 8 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 9 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 10 | /*!40101 SET NAMES utf8mb4 */; 11 | /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; 12 | /*!40103 SET TIME_ZONE='+00:00' */; 13 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 14 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 15 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 16 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 17 | 18 | -- 19 | -- Table structure for table `continents` 20 | -- 21 | 22 | DROP TABLE IF EXISTS `continents`; 23 | /*!40101 SET @saved_cs_client = @@character_set_client */; 24 | /*!40101 SET character_set_client = utf8mb4 */; 25 | CREATE TABLE `continents` ( 26 | `ContinentID` int(11) NOT NULL AUTO_INCREMENT, 27 | `Continent` varchar(13) DEFAULT NULL, 28 | PRIMARY KEY (`ContinentID`) 29 | ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 30 | /*!40101 SET character_set_client = @saved_cs_client */; 31 | 32 | -- 33 | -- Dumping data for table `continents` 34 | -- 35 | 36 | LOCK TABLES `continents` WRITE; 37 | /*!40000 ALTER TABLE `continents` DISABLE KEYS */; 38 | INSERT INTO `continents` VALUES (1,'Africa'),(2,'Asia'),(3,'Europe'),(4,'North America'),(5,'Oceania'),(6,'South America'); 39 | /*!40000 ALTER TABLE `continents` ENABLE KEYS */; 40 | UNLOCK TABLES; 41 | 42 | -- 43 | -- Table structure for table `country` 44 | -- 45 | 46 | DROP TABLE IF EXISTS `country`; 47 | /*!40101 SET @saved_cs_client = @@character_set_client */; 48 | /*!40101 SET character_set_client = utf8mb4 */; 49 | CREATE TABLE `country` ( 50 | `CountryID` int(11) NOT NULL AUTO_INCREMENT, 51 | `Country Code` varchar(5) DEFAULT NULL, 52 | `Country Name` varchar(50) DEFAULT NULL, 53 | `ContinentID` int(11) DEFAULT NULL, 54 | PRIMARY KEY (`CountryID`) 55 | ) ENGINE=InnoDB AUTO_INCREMENT=264 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 56 | /*!40101 SET character_set_client = @saved_cs_client */; 57 | 58 | -- 59 | -- Dumping data for table `country` 60 | -- 61 | 62 | LOCK TABLES `country` WRITE; 63 | /*!40000 ALTER TABLE `country` DISABLE KEYS */; 64 | INSERT INTO `country` VALUES (1,'ABW','Aruba',4),(2,'AFG','Afghanistan',2),(3,'AGO','Angola',1),(4,'ALB','Albania',3),(5,'AND','Andorra',3),(6,'ARB','Arab World',NULL),(7,'ARE','United Arab Emirates',2),(8,'ARG','Argentina',6),(9,'ARM','Armenia',2),(10,'ASM','American Samoa',5),(11,'ATG','Antigua and Barbuda',4),(12,'AUS','Australia',5),(13,'AUT','Austria',3),(14,'AZE','Azerbaijan',2),(15,'BDI','Burundi',1),(16,'BEL','Belgium',3),(17,'BEN','Benin',1),(18,'BFA','Burkina Faso',1),(19,'BGD','Bangladesh',2),(20,'BGR','Bulgaria',3),(21,'BHR','Bahrain',2),(22,'BHS','Bahamas, The',4),(23,'BIH','Bosnia and Herzegovina',3),(24,'BLR','Belarus',3),(25,'BLZ','Belize',4),(26,'BMU','Bermuda',4),(27,'BOL','Bolivia',6),(28,'BRA','Brazil',6),(29,'BRB','Barbados',4),(30,'BRN','Brunei Darussalam',2),(31,'BTN','Bhutan',2),(32,'BWA','Botswana',1),(33,'CAF','Central African Republic',1),(34,'CAN','Canada',4),(35,'CEB','Central Europe and the Baltics',NULL),(36,'CHE','Switzerland',3),(37,'CHI','Channel Islands',NULL),(38,'CHL','Chile',6),(39,'CHN','China',2),(40,'CIV','Cote d\'Ivoire',1),(41,'CMR','Cameroon',1),(42,'COD','Congo, Dem. Rep.',1),(43,'COG','Congo, Rep.',1),(44,'COL','Colombia',6),(45,'COM','Comoros',1),(46,'CPV','Cabo Verde',1),(47,'CRI','Costa Rica',4),(48,'CSS','Caribbean small states',NULL),(49,'CUB','Cuba',4),(50,'CUW','Curacao',NULL),(51,'CYM','Cayman Islands',4),(52,'CYP','Cyprus',2),(53,'CZE','Czech Republic',3),(54,'DEU','Germany',3),(55,'DJI','Djibouti',1),(56,'DMA','Dominica',4),(57,'DNK','Denmark',3),(58,'DOM','Dominican Republic',4),(59,'DZA','Algeria',1),(60,'EAP','East Asia & Pacific (excluding high income)',NULL),(61,'EAR','Early-demographic dividend',NULL),(62,'EAS','East Asia & Pacific',NULL),(63,'ECA','Europe & Central Asia (excluding high income)',NULL),(64,'ECS','Europe & Central Asia',NULL),(65,'ECU','Ecuador',6),(66,'EGY','Egypt, Arab Rep.',1),(67,'EMU','Euro area',NULL),(68,'ERI','Eritrea',1),(69,'ESP','Spain',3),(70,'EST','Estonia',3),(71,'ETH','Ethiopia',1),(72,'EUU','European Union',NULL),(73,'FCS','Fragile and conflict affected situations',NULL),(74,'FIN','Finland',3),(75,'FJI','Fiji',5),(76,'FRA','France',3),(77,'FRO','Faroe Islands',3),(78,'FSM','Micronesia, Fed. Sts.',5),(79,'GAB','Gabon',1),(80,'GBR','United Kingdom',3),(81,'GEO','Georgia',2),(82,'GHA','Ghana',1),(83,'GIB','Gibraltar',3),(84,'GIN','Guinea',1),(85,'GMB','Gambia, The',1),(86,'GNB','Guinea-Bissau',1),(87,'GNQ','Equatorial Guinea',1),(88,'GRC','Greece',3),(89,'GRD','Grenada',4),(90,'GRL','Greenland',4),(91,'GTM','Guatemala',4),(92,'GUM','Guam',5),(93,'GUY','Guyana',6),(94,'HIC','High income',NULL),(95,'HKG','Hong Kong SAR, China',2),(96,'HND','Honduras',4),(97,'HPC','Heavily indebted poor countries (HIPC)',NULL),(98,'HRV','Croatia',3),(99,'HTI','Haiti',4),(100,'HUN','Hungary',3),(101,'IBD','IBRD only',NULL),(102,'IBT','IDA & IBRD total',NULL),(103,'IDA','IDA total',NULL),(104,'IDB','IDA blend',NULL),(105,'IDN','Indonesia',2),(106,'IDX','IDA only',NULL),(107,'IMN','Isle of Man',NULL),(108,'IND','India',2),(109,'IRL','Ireland',3),(110,'IRN','Iran, Islamic Rep.',2),(111,'IRQ','Iraq',2),(112,'ISL','Iceland',3),(113,'ISR','Israel',2),(114,'ITA','Italy',3),(115,'JAM','Jamaica',4),(116,'JOR','Jordan',2),(117,'JPN','Japan',2),(118,'KAZ','Kazakhstan',2),(119,'KEN','Kenya',1),(120,'KGZ','Kyrgyz Republic',2),(121,'KHM','Cambodia',2),(122,'KIR','Kiribati',5),(123,'KNA','St. Kitts and Nevis',4),(124,'KOR','Korea, Rep.',2),(125,'KWT','Kuwait',2),(126,'LAC','Latin America & Caribbean (excluding high income)',NULL),(127,'LAO','Lao PDR',2),(128,'LBN','Lebanon',2),(129,'LBR','Liberia',1),(130,'LBY','Libya',1),(131,'LCA','St. Lucia',4),(132,'LCN','Latin America & Caribbean',NULL),(133,'LDC','Least developed countries: UN classification',NULL),(134,'LIC','Low income',NULL),(135,'LIE','Liechtenstein',3),(136,'LKA','Sri Lanka',2),(137,'LMC','Lower middle income',NULL),(138,'LMY','Low & middle income',NULL),(139,'LSO','Lesotho',1),(140,'LTE','Late-demographic dividend',NULL),(141,'LTU','Lithuania',3),(142,'LUX','Luxembourg',3),(143,'LVA','Latvia',3),(144,'MAC','Macao SAR, China',2),(145,'MAF','St. Martin (French part)',NULL),(146,'MAR','Morocco',1),(147,'MCO','Monaco',3),(148,'MDA','Moldova',3),(149,'MDG','Madagascar',1),(150,'MDV','Maldives',2),(151,'MEA','Middle East & North Africa',NULL),(152,'MEX','Mexico',4),(153,'MHL','Marshall Islands',5),(154,'MIC','Middle income',NULL),(155,'MKD','Macedonia, FYR',3),(156,'MLI','Mali',1),(157,'MLT','Malta',3),(158,'MMR','Myanmar',2),(159,'MNA','Middle East & North Africa (excluding high income)',NULL),(160,'MNE','Montenegro',NULL),(161,'MNG','Mongolia',2),(162,'MNP','Northern Mariana Islands',5),(163,'MOZ','Mozambique',1),(164,'MRT','Mauritania',1),(165,'MUS','Mauritius',1),(166,'MWI','Malawi',1),(167,'MYS','Malaysia',2),(168,'NAC','North America',NULL),(169,'NAM','Namibia',1),(170,'NCL','New Caledonia',5),(171,'NER','Niger',1),(172,'NGA','Nigeria',1),(173,'NIC','Nicaragua',4),(174,'NLD','Netherlands',3),(175,'NOR','Norway',3),(176,'NPL','Nepal',2),(177,'NRU','Nauru',5),(178,'NZL','New Zealand',5),(179,'OED','OECD members',NULL),(180,'OMN','Oman',2),(181,'OSS','Other small states',NULL),(182,'PAK','Pakistan',2),(183,'PAN','Panama',4),(184,'PER','Peru',6),(185,'PHL','Philippines',2),(186,'PLW','Palau',5),(187,'PNG','Papua New Guinea',5),(188,'POL','Poland',3),(189,'PRE','Pre-demographic dividend',NULL),(190,'PRI','Puerto Rico',4),(191,'PRK','Korea, Dem. People\'s Rep.',2),(192,'PRT','Portugal',3),(193,'PRY','Paraguay',6),(194,'PSE','West Bank and Gaza',2),(195,'PSS','Pacific island small states',NULL),(196,'PST','Post-demographic dividend',NULL),(197,'PYF','French Polynesia',5),(198,'QAT','Qatar',2),(199,'ROU','Romania',NULL),(200,'RUS','Russian Federation',3),(201,'RWA','Rwanda',1),(202,'SAS','South Asia',NULL),(203,'SAU','Saudi Arabia',2),(204,'SDN','Sudan',1),(205,'SEN','Senegal',1),(206,'SGP','Singapore',2),(207,'SLB','Solomon Islands',5),(208,'SLE','Sierra Leone',1),(209,'SLV','El Salvador',4),(210,'SMR','San Marino',3),(211,'SOM','Somalia',1),(212,'SRB','Serbia',NULL),(213,'SSA','Sub-Saharan Africa (excluding high income)',NULL),(214,'SSD','South Sudan',NULL),(215,'SSF','Sub-Saharan Africa',NULL),(216,'SST','Small states',NULL),(217,'STP','Sao Tome and Principe',1),(218,'SUR','Suriname',6),(219,'SVK','Slovak Republic',3),(220,'SVN','Slovenia',3),(221,'SWE','Sweden',3),(222,'SWZ','Eswatini',1),(223,'SXM','Sint Maarten (Dutch part)',NULL),(224,'SYC','Seychelles',1),(225,'SYR','Syrian Arab Republic',2),(226,'TCA','Turks and Caicos Islands',4),(227,'TCD','Chad',1),(228,'TEA','East Asia & Pacific (IDA & IBRD)',NULL),(229,'TEC','Europe & Central Asia (IDA & IBRD)',NULL),(230,'TGO','Togo',1),(231,'THA','Thailand',2),(232,'TJK','Tajikistan',2),(233,'TKM','Turkmenistan',2),(234,'TLA','Latin America & Caribbean (IDA & IBRD)',NULL),(235,'TLS','Timor-Leste',NULL),(236,'TMN','Middle East & North Africa (IDA & IBRD)',NULL),(237,'TON','Tonga',5),(238,'TSA','South Asia (IDA & IBRD)',NULL),(239,'TSS','Sub-Saharan Africa (IDA & IBRD)',NULL),(240,'TTO','Trinidad and Tobago',4),(241,'TUN','Tunisia',1),(242,'TUR','Turkey',2),(243,'TUV','Tuvalu',5),(244,'TZA','Tanzania',1),(245,'UGA','Uganda',1),(246,'UKR','Ukraine',3),(247,'UMC','Upper middle income',NULL),(248,'URY','Uruguay',6),(249,'USA','United States',4),(250,'UZB','Uzbekistan',2),(251,'VCT','St. Vincent and the Grenadines',4),(252,'VEN','Venezuela, RB',6),(253,'VGB','British Virgin Islands',4),(254,'VIR','Virgin Islands (U.S.)',4),(255,'VNM','Vietnam',2),(256,'VUT','Vanuatu',5),(257,'WLD','World',NULL),(258,'WSM','Samoa',5),(259,'XKX','Kosovo',NULL),(260,'YEM','Yemen, Rep.',2),(261,'ZAF','South Africa',1),(262,'ZMB','Zambia',1),(263,'ZWE','Zimbabwe',1); 65 | /*!40000 ALTER TABLE `country` ENABLE KEYS */; 66 | UNLOCK TABLES; 67 | /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; 68 | 69 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 70 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 71 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 72 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 73 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 74 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 75 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 76 | 77 | -- Dump completed on 2019-09-26 20:49:42 78 | -------------------------------------------------------------------------------- /Chapter07/Databases/mysqlconnection1.js: -------------------------------------------------------------------------------- 1 | //This is the final incarnation of the mysqlconnection script 2 | //it is now a module that can be reused. 3 | //By setting this connection script up as a module, you only need to 4 | //put the connection details in here and NOT in other scripts 5 | //If the details change in the future, you only need to change them here, once, all other scripts 6 | //using the module will still connect, so much easier for maintenance 7 | 8 | 9 | //Include the sql2 module so we can connect to the database server 10 | var mysql = require('mysql2'); 11 | 12 | //Create the connection 13 | var mysqlconnection = mysql.createConnection({ 14 | host: "192.168.0.2", 15 | port: "3306", //This will usually be 3306 but can be changed on the server or if the server is on the internet 16 | user: "root", 17 | password: "" 18 | }); 19 | 20 | 21 | //Start the Connection Block 22 | //Make the connection, include error checking 23 | mysqlconnection.connect(function(err) { 24 | 25 | //Test for an error and provide a suitable message and the code if one occurs 26 | if (err) throw "mysqlconnection.js problem connecting to MySQL, the ERROR CODE is :-" + err.code; 27 | 28 | //No error so report to the console that connection was successful 29 | //This can be omitted 30 | console.log("Connected to MySQL!"); 31 | 32 | 33 | //Close off the connection blocks bracketing 34 | }); 35 | 36 | //End the Connection Block 37 | 38 | //This is the magic line, it allows the object mysqlconnection to be exported 39 | //which means other scripts can .require(myqlconnection) and use the connection...so cool 40 | module.exports = mysqlconnection; 41 | 42 | //No requirement for a process.exit in this script -------------------------------------------------------------------------------- /Chapter07/Databases/mysqlconnection2.js: -------------------------------------------------------------------------------- 1 | //This is the final incarnation of the mysqlconnection script 2 | //it is now a module that can be reused. 3 | //By setting this connection script up as a module, you only need to 4 | //put the connection details in here and NOT in other scripts 5 | //If the details change in the future, you only need to change them here, once, all other scripts 6 | //using the module will still connect, so much easier for maintenance 7 | 8 | 9 | //Include the sql2 module so we can connect to the database server 10 | var mysql = require('mysql2'); 11 | 12 | //Create the connection 13 | var mysqlconnection = mysql.createConnection({ 14 | host: "localhost", 15 | port: "3306", //This will usually be 3306 but can be changed on the server or if the server is on the internet 16 | user: "root2", 17 | password: "" 18 | }); 19 | 20 | 21 | //Start the Connection Block 22 | //Make the connection, include error checking 23 | mysqlconnection.connect(function(err) { 24 | 25 | //Test for an error and provide a suitable message and the code if one occurs 26 | if (err) throw "mysqlconnection.js problem connecting to MySQL, the ERROR CODE is :-" + err.code; 27 | 28 | //No error so report to the console that connection was successful 29 | //This can be omitted 30 | console.log("Connected to MySQL!"); 31 | 32 | 33 | //Close off the connection blocks bracketing 34 | }); 35 | 36 | //End the Connection Block 37 | 38 | //This is the magic line, it allows the object mysqlconnection to be exported 39 | //which means other scripts can .require(myqlconnection) and use the connection...so cool 40 | module.exports = mysqlconnection; 41 | 42 | //No requirement for a process.exit in this script -------------------------------------------------------------------------------- /Chapter07/Exercise7.01/exercise.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM backuppractice.country; 2 | 3 | SELECT * FROM backuppractice.country 4 | WHERE `Country Code`="AUS" 5 | 6 | DELETE FROM backuppractice.country 7 | WHERE `Country Code`="AUS"; 8 | 9 | SELECT * FROM backuppractice.country 10 | WHERE `Country Code`="AUS"; 11 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.02/Add-OutToConsole.js: -------------------------------------------------------------------------------- 1 | console.log(3+4); -------------------------------------------------------------------------------- /Chapter07/Exercise7.03/Add-OutToBrowser.js: -------------------------------------------------------------------------------- 1 | //Verified all code 2 | 3 | //Output the message to the browser 4 | //Include the http module to allow output to the browser 5 | var http = require('http'); 6 | 7 | //Create a server to monitor the port for a request 8 | http.createServer(function (req, res) { 9 | res.writeHead(200, {'Content-Type': 'text/html'}); 10 | 11 | var result = 4+4; 12 | //Output the text and the date serial in response to a request 13 | res.end(result.toString()); 14 | 15 | //Close off the server bracketing and instruct server to list to port 82 for requests 16 | }).listen(82); 17 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.04/Log-ToDiskFile.js: -------------------------------------------------------------------------------- 1 | //Verified 2 | //Outputs data to a disk file 3 | 4 | //Include the File System module to work with disk files 5 | var fs = require('fs'); 6 | 7 | //Creates the file into object stream and names the file 8 | var stream = fs.createWriteStream("Log.txt"); 9 | 10 | //Output data to the file. 11 | stream.write("Application Started Successfully!\n"); // the \n forces a new line 12 | 13 | //Ends the stream and closes the file 14 | stream.end(); 15 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.04/Log.txt: -------------------------------------------------------------------------------- 1 | Application Started Successfully! 2 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.05/MySQLConnection.js: -------------------------------------------------------------------------------- 1 | //Verified 2 | //This is the final incarnation of the mysqlconnection script 3 | //it is now a module that can be reused. 4 | //By setting this connection script up as a module, you only need to 5 | //put the connection details in here and NOT in other scripts 6 | //If the details change in the future, you only need to change them here, once, all other scripts 7 | //using the module will still connect, so much easier for maintenance 8 | 9 | 10 | //Include the sql2 module so we can connect to the database server 11 | var mysql = require('mysql'); 12 | 13 | //Create the connection 14 | var mysqlconnection = mysql.createConnection({ 15 | host: "", 16 | port: "3306", //This will usually be 3306 but can be changed on the server or if the server is on the internet 17 | user: "", 18 | password: "" 19 | }); 20 | 21 | 22 | //Start the Connection Block 23 | //Make the connection, include error checking 24 | mysqlconnection.connect(function(err) { 25 | 26 | //Test for an error and provide a suitable message and the code if one occurs 27 | if (err){ 28 | throw err; 29 | }else{ 30 | //No error so report to the console that connection was successful 31 | //This can be omitted 32 | console.log("Connected to MySQL!"); 33 | } 34 | process.exit(); 35 | 36 | //Close off the connection blocks bracketing 37 | }); 38 | 39 | //End the Connection Block 40 | 41 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.06/MySQLConnection.js: -------------------------------------------------------------------------------- 1 | //This is the final incarnation of the mysqlconnection script 2 | //it is now a module that can be reused. 3 | //By setting this connection script up as a module, you only need to 4 | //put the connection details in here and NOT in other scripts 5 | //If the details change in the future, you only need to change them here, once, all other scripts 6 | //using the module will still connect, so much easier for maintenance 7 | 8 | 9 | //Include the sql2 module so we can connect to the database server 10 | var mysql = require('mysql2'); 11 | 12 | //Create the connection 13 | var mysqlconnection = mysql.createConnection({ 14 | host: "", 15 | port: "3306", //This will usually be 3306 but can be changed on the server or if the server is on the internet 16 | user: "", 17 | password: "" 18 | }); 19 | 20 | 21 | //Start the Connection Block 22 | //Make the connection, include error checking 23 | mysqlconnection.connect(function(err) { 24 | 25 | //Test for an error and provide a suitable message and the code if one occurs 26 | if (err){ 27 | throw err; 28 | }else{ 29 | //No error so report to the console that connection was successful 30 | //This can be omitted 31 | console.log("Connected to MySQL!"); 32 | } 33 | 34 | //Close off the connection blocks bracketing 35 | }); 36 | 37 | //End the Connection Block 38 | 39 | //This is the magic line, it allows the object mysqlconnection to be exported 40 | //which means other scripts can .require(myqlconnection) and use the connection...so cool 41 | module.exports = mysqlconnection; 42 | 43 | //No requirement for a process.exit in this script -------------------------------------------------------------------------------- /Chapter07/Exercise7.06/TestModule.js: -------------------------------------------------------------------------------- 1 | //Verified 2 | 3 | var mysqlconnection = require("./mysqlconnection.js"); 4 | 5 | mysqlconnection.query("SELECT Count(*) AS CountryCount \ 6 | FROM backuppractice.country;", function (err, SQLresult) { 7 | 8 | if (err) throw "Problem counting Countries:- " + err.code; 9 | console.log("Country count :- " + SQLresult[0].CountryCount); 10 | process.exit(); 11 | 12 | }); 13 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.07/MySQLCreateDatabase.js: -------------------------------------------------------------------------------- 1 | //Verified 2 | //This script uses the mysqlconnection as a module so does not require the connection details 3 | //for the database, these are included when the module is required 4 | 5 | //Bring in the mysqlconnection module, sure save time... 6 | //and if the server or user account changes later, no need to worry about it here 7 | //as long asthey are updated in the mysqlconnection.js module 8 | var mysqlconnection = require("../mysqlconnection.js"); 9 | 10 | //You can issue commands to the server via an SQL statement 11 | //Here we are issuing a server command to create a new database 12 | //We are including error checking 13 | mysqlconnection.query("CREATE DATABASE `world_statistics`", 14 | function (err) { 15 | 16 | //If there was and error, tell the user, along with the error code 17 | if (err) throw "Problem creating the database:- " + 18 | err.code; 19 | 20 | //No error, tell user the database was created 21 | console.log("Database created"); 22 | 23 | //And leave the script 24 | process.exit(); 25 | 26 | //Closing off the bracketing 27 | }); 28 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.08/MySQLCreateTable.js: -------------------------------------------------------------------------------- 1 | //Verified 2 | //Here we are going to add a table to the new database 3 | //Again...and this will be in all subsequent scripts, include the mysqlconnection module 4 | //Oh the joy of not rewriting all that connection stuff 5 | var mysqlconnection = require("../mysqlconnection.js"); 6 | 7 | //Issue a server command to create the table. The command also defines the fields and their data type 8 | //The ID field is also designated as the prinary key, it is an integer and will auto increment its value 9 | //as each recor is inserted into the table 10 | var sql = "CREATE TABLE `world_statistics`.`continents` ( \ 11 | `ContinentID` int(11) NOT NULL AUTO_INCREMENT, \ 12 | `Continent` varchar(13) DEFAULT NULL, \ 13 | PRIMARY KEY (`ContinentID`)\ 14 | );" 15 | 16 | 17 | //Execute the SQL, in clude error checking 18 | mysqlconnection.query(sql, function (err) { 19 | 20 | //Handle any errors 21 | if (err) throw "Problem creating the table:- " + err.code; 22 | 23 | //Otherwise tell user that the table was created 24 | console.log("Table created"); 25 | 26 | //And leave 27 | process.exit(); 28 | 29 | //Close off the block bracketing 30 | }); 31 | -------------------------------------------------------------------------------- /Chapter07/mysqlconnection.js: -------------------------------------------------------------------------------- 1 | //This is the final incarnation of the mysqlconnection script 2 | //it is now a module that can be reused. 3 | //By setting this connection script up as a module, you only need to 4 | //put the connection details in here and NOT in other scripts 5 | //If the details change in the future, you only need to change them here, once, all other scripts 6 | //using the module will still connect, so much easier for maintenance 7 | 8 | 9 | //Include the sql2 module so we can connect to the database server 10 | var mysql = require('mysql2'); 11 | 12 | //Create the connection 13 | var mysqlconnection = mysql.createConnection({ 14 | host: "localhost", 15 | port: "3306", //This will usually be 3306 but can be changed on the server or if the server is on the internet 16 | user: "root", 17 | password: "" 18 | }); 19 | 20 | 21 | //Start the Connection Block 22 | //Make the connection, include error checking 23 | mysqlconnection.connect(function(err) { 24 | 25 | //Test for an error and provide a suitable message and the code if one occurs 26 | if (err) throw "mysqlconnection.js problem connecting to MySQL, the ERROR CODE is :-" + err.code; 27 | 28 | //No error so report to the console that connection was successful 29 | //This can be omitted 30 | console.log("Connected to MySQL!"); 31 | 32 | 33 | //Close off the connection blocks bracketing 34 | }); 35 | 36 | //End the Connection Block 37 | 38 | //This is the magic line, it allows the object mysqlconnection to be exported 39 | //which means other scripts can .require(myqlconnection) and use the connection...so cool 40 | module.exports = mysqlconnection; 41 | 42 | //No requirement for a process.exit in this script -------------------------------------------------------------------------------- /Chapter07/node_modules.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter07/node_modules.zip -------------------------------------------------------------------------------- /Chapter08/Activity8.01/Activity-MultipleUpdates.js: -------------------------------------------------------------------------------- 1 | var mysqlconnection = require("./mysqlconnection.js") 2 | mysqlconnection.query("USE world_statistics", function (err, result) { 3 | if (err) throw "Instructing database to use" + err.code; 4 | //Tell user on console 5 | console.log("Using World_Statistics"); 6 | var newfield = "CREATE TABLE countryalldetails(CountryID INT(11), ContinentID INT(11), `Country Code` VARCHAR(5), `Country Name` VARCHAR(50))”; 7 | 8 | mysqlconnection.query(newfield, function (err, result) { 9 | //Deal with the error should one occur 10 | if (err) throw "Problem creating column Capital" + err.code; 11 | //Tell user that the capital column has been created 12 | console.log("Column Capital created"); 13 | }); 14 | 15 | var newfield = "ALTER TABLE countryalldetails ADD COLUMN Is_Independent VARCHAR(25);" 16 | 17 | mysqlconnection.query(newfield, function (err, result) { 18 | //Deal with the error should one occur 19 | if (err) throw "Problem creating column Is_Independent" + err.code; 20 | //Tell user that the Is_Independent column has been created 21 | console.log("Column Is_Independent created"); 22 | }); 23 | 24 | var newfield = "ALTER TABLE countryalldetails ADD COLUMN Currency VARCHAR(5);" 25 | mysqlconnection.query(newfield, function (err, result) { 26 | //Deal with the error should one occur 27 | if (err) throw "Problem creating column Currency" + err.code; 28 | //Tell user that the currency column has been created 29 | console.log("Column Currency created"); 30 | }); 31 | 32 | var updateOne="UPDATE countryalldetails SET Capital = " 33 | updateOne = updateOne + "(SELECT `Capital` FROM world_statistics.temp WHERE `Country Code`= `country`.`Country Code` LIMIT 1);" 34 | 35 | mysqlconnection.query(updateOne, function (err, result) { 36 | if (err) throw "Problem updating Capital" + err.code; 37 | //Tell user that the capital is updated, and show affectedRows 38 | console.log("Capital is updated"); 39 | console.log("Number of rows affected : " + result.affectedRows); 40 | }); 41 | 42 | var updateTwo="UPDATE countryalldetails SET Is_Independent = " 43 | updateTwo = updateTwo + "(SELECT `Is_Independent` FROM world_statistics.temp WHERE `Country Code`= `country`.`Country Code` LIMIT 1);" 44 | 45 | mysqlconnection.query(updateTwo, function (err, result) { 46 | if (err) throw "Problem updating Is_Independent" + err.code; 47 | //Tell user that the Is_Independent column has been updated 48 | console.log("Is_Independent is updated"); 49 | console.log("Number of rows affected : " + result.affectedRows); 50 | }); 51 | 52 | var updateThree="UPDATE country SET Currency = " 53 | updateThree = updateThree + "(SELECT `Currency` FROM world_statistics.temp WHERE `Country Code`= `country`.`Country Code` LIMIT 1);" 54 | mysqlconnection.query(updateThree, function (err, result) { 55 | if (err) throw "Problem updating Currency" + err.code; 56 | //Tell user that the currency column has been updated 57 | console.log("Currency is updated"); 58 | console.log("Number of rows affected : " + result.affectedRows); 59 | process.exit(); 60 | }); 61 | 62 | });//USE world_statistics 63 | -------------------------------------------------------------------------------- /Chapter08/Activity8.01/CountryDetails.sql: -------------------------------------------------------------------------------- 1 | -- Table structure for table `temp` 2 | -- 3 | USE world_statistics; 4 | 5 | DROP TABLE IF EXISTS `temp`; 6 | /*!40101 SET @saved_cs_client = @@character_set_client */; 7 | /*!50503 SET character_set_client = utf8mb4 */; 8 | CREATE TABLE `temp` ( 9 | `Country Code` varchar(5) DEFAULT NULL, 10 | `Capital` varchar(50) DEFAULT NULL, 11 | `Is_Independent` varchar(25) DEFAULT NULL, 12 | `Currency` varchar(5) DEFAULT NULL 13 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 14 | /*!40101 SET character_set_client = @saved_cs_client */; 15 | 16 | -- 17 | -- Dumping data for table `temp` 18 | -- 19 | 20 | LOCK TABLES `temp` WRITE; 21 | /*!40000 ALTER TABLE `temp` DISABLE KEYS */; 22 | INSERT INTO `temp` VALUES ('AFG','Kabul','Yes','AFN'),('ALB','Tirana','Yes','ALL'),('DZA','Algiers','Yes','DZD'),('ASM','Pago Pago','Territory of US','USD'),('AND','Andorra la Vella','Yes','EUR'),('AGO','Luanda','Yes','AOA'),('AIA','The Valley','Territory of GB','XCD'),('ATA',NULL,'International',NULL),('ATG','St. John\'s','Yes','XCD'),('ARG','Buenos Aires','Yes','ARS'),('ARM','Yerevan','Yes','AMD'),('ABW','Oranjestad','Part of NL','AWG'),('AUS','Canberra','Yes','AUD'),('AUT','Vienna','Yes','EUR'),('AZE','Baku','Yes','AZN'),('BHS','Nassau','Yes','BSD'),('BHR','Manama','Yes','BHD'),('BGD','Dhaka','Yes','BDT'),('BRB','Bridgetown','Yes','BBD'),('BLR','Minsk','Yes','BYR'),('BEL','Brussels','Yes','EUR'),('BLZ','Belmopan','Yes','BZD'),('BEN','Porto-Novo','Yes','XOF'),('BMU','Hamilton','Territory of GB','BMD'),('BTN','Thimphu','Yes','INR'),('BOL','Yes','68','BOB'),('BIH','Sarajevo','Yes','BAM'),('BWA','Gaborone','Yes','BWP'),('BVT',NULL,'Territory of NO',NULL),('BRA','Brasilia','Yes','BRL'),('IOT','Diego Garcia','Territory of GB',NULL),('VGB','Road Town','Territory of GB','USD'),('BRN','Bandar Seri Begawan','Yes','BND'),('BGR','Sofia','Yes','BGN'),('BFA','Ouagadougou','Yes','XOF'),('BDI','Bujumbura','Yes','BIF'),('KHM','Phnom Penh','Yes','KHR'),('CMR','Yaounde','Yes','XAF'),('CAN','Ottawa','Yes','CAD'),('CPV','Praia','Yes','CVE'),('BQ','840','US Dollar','AHO'),('CYM','George Town','Territory of GB','KYD'),('CAF','Bangui','Yes','XAF'),('TCD','N\'Djamena','Yes','XAF'),('CHL','Santiago','Yes','CLP'),('CHN','Beijing','Yes','CNY'),('CXR','Flying Fish Cove','Territory of AU',NULL),('CCK','West Island','Territory of AU',NULL),('COL','Bogota','Yes','COP'),('COM','Moroni','Yes','KMF'),('COG','Brazzaville','Yes','XAF'),('COD','Kinshasa','Yes',NULL),('COK','Avarua','Associated with NZ','NZD'),('CRI','San Jose','Yes','CRC'),('HRV','Zagreb','Yes','HRK'),('CUB','Havana','Yes','CUP'),('CUW','Willemstad','Part of NL','ANG'),('CYP','Nicosia','Yes','EUR'),('CZE','Prague','Yes',NULL),('CIV','Yamoussoukro','Yes','XOF'),('DNK','Copenhagen','Yes','DKK'),('DJI','Djibouti','Yes','DJF'),('DMA','Roseau','Yes','XCD'),('DOM','214','Dominican Peso','72'),('ECU','Quito','Yes','USD'),('EGY','Cairo','Yes','EGP'),('SLV','San Salvador','Yes','USD'),('GNQ','Malabo','Yes','XAF'),('ERI','Asmara','Yes','ERN'),('EST','Tallinn','Yes','EUR'),('ETH','Addis Ababa','Yes','ETB'),('FLK','Stanley','Territory of GB','FKP'),('FRO','Torshavn','Part of DK',NULL),('FJI','Suva','Yes','FJD'),('FIN','Helsinki','Yes','EUR'),('FRA','Paris','Yes','EUR'),('GUF','Cayenne','Part of FR','EUR'),('PYF','Papeete','Territory of FR','XPF'),('ATF','Port-aux-Francais','Territory of FR',NULL),('GAB','Libreville','Yes','XAF'),('GMB','Banjul','Yes','GMD'),('GEO','Tbilisi','Yes','GEL'),('DEU','Berlin','Yes','EUR'),('GHA','Accra','Yes','GHS'),('GIB','Gibraltar','Territory of GB','GIP'),('GRC','Athens','Yes','EUR'),('GRL','Nuuk','Part of DK','DKK'),('GRD','St. George\'s','Yes','XCD'),('GLP','Basse-Terre','Part of FR','EUR'),('GUM','Hagatna','Territory of US','USD'),('GTM','Guatemala City','Yes','GTQ'),('GGY','St Peter Port','Crown dependency of GB','GBP'),('GIN','Conakry','Yes','GNF'),('GNB','Bissau','Yes','XOF'),('GUY','Georgetown','Yes','GYD'),('HTI','Port-au-Prince','Yes','USD'),('HMD',NULL,'Territory of AU',NULL),('HND','Tegucigalpa','Yes','HNL'),('HK','Part of CN',NULL,'HKG'),('HUN','Budapest','Yes','HUF'),('ISL','Reykjavik','Yes','ISK'),('IND','New Delhi','Yes','INR'),('IDN','Jakarta','Yes','IDR'),('IRN','Yes','364','IRR'),('IRQ','Baghdad','Yes','IQD'),('IRL','Dublin','Yes','EUR'),('IMN','Douglas','Crown dependency of GB','GBP'),('ISR','Jerusalem','Yes','ILS'),('ITA','Rome','Yes','EUR'),('JAM','Kingston','Yes','JMD'),('JPN','Tokyo','Yes','JPY'),('JEY','Saint Helier','Crown dependency of GB','GBP'),('JOR','Amman','Yes','JOD'),('KAZ','Astana','Yes','KZT'),('KEN','Nairobi','Yes','KES'),('KIR','Tarawa','Yes','AUD'),('KWT','Kuwait City','Yes','KWD'),('KGZ','Bishkek','Yes','KGS'),('LAO','Vientiane','Yes','LAK'),('LVA','Riga','Yes','EUR'),('LBN','Beirut','Yes','LBP'),('LSO','Maseru','Yes','ZAR'),('LBR','Monrovia','Yes','LRD'),('LBY','Tripoli','Yes','LYD'),('LIE','Vaduz','Yes','CHF'),('LTU','Vilnius','Yes','EUR'),('LUX','Luxembourg','Yes','EUR'),('MO','Part of CN','446','MAC'),('MKD','Yes','807','MKD'),('MDG','Antananarivo','Yes','MGA'),('MWI','Lilongwe','Yes','MWK'),('MYS','Kuala Lumpur','Yes','MYR'),('MDV','Male','Yes','MVR'),('MLI','Bamako','Yes','XOF'),('MLT','Valletta','Yes','EUR'),('MHL','Majuro','Yes','USD'),('MTQ','Fort-de-France','Part of FR','EUR'),('MRT','Nouakchott','Yes','MRO'),('MUS','Port Louis','Yes','MUR'),('MYT','Mamoudzou','Part of FR','EUR'),('MEX','Mexico City','Yes','MXN'),('FSM','Yes','840','USD'),('MDA','Yes','498','MDL'),('MCO','Monaco','Yes','EUR'),('MNG','Ulan Bator','Yes','MNT'),('MNE','Podgorica','Yes','EUR'),('MSR','Plymouth','Territory of GB','XCD'),('MAR','Rabat','Yes','MAD'),('MOZ','Maputo','Yes','MZN'),('MMR','Nay Pyi Taw','Yes','MMK'),('NAM','Windhoek','Yes','ZAR'),('NRU','Yaren','Yes','AUD'),('NPL','Kathmandu','Yes','NPR'),('NLD','Amsterdam','Yes','EUR'),('NCL','Noumea','Territory of FR','XPF'),('NZL','Wellington','Yes','NZD'),('NIC','Managua','Yes','NIO'),('NER','Niamey','Yes','XOF'),('NGA','Abuja','Yes','NGN'),('NIU','Alofi','Associated with NZ','NZD'),('NFK','Kingston','Territory of AU','AUD'),('PRK','Yes','408','KPW'),('MNP','Saipan','Commonwealth of US','USD'),('NOR','Oslo','Yes','NOK'),('OMN','Muscat','Yes','OMR'),('PAK','Islamabad','Yes','PKR'),('PLW','Melekeok','Yes','USD'),('PSE',NULL,'STATE OF\"','\"91'),('PAN','Panama City','Yes','USD'),('PNG','Port Moresby','Yes','PGK'),('PRY','Asuncion','Yes','PYG'),('PER','Lima','Yes','PEN'),('PHL','Manila','Yes','PHP'),('PCN','Adamstown','Territory of GB','NZD'),('POL','Warsaw','Yes','PLN'),('PRT','Lisbon','Yes','EUR'),('PRI','San Juan','Commonwealth of US','USD'),('QAT','Doha','Yes','QAR'),('ROU','Bucharest','Yes','RON'),('RUS','Moscow','Yes','RUB'),('RWA','Kigali','Yes','RWF'),('REU','Saint-Denis','Part of FR','EUR'),('WSM','Apia','Yes','WST'),('SMR','San Marino','Yes','EUR'),('SAU','Riyadh','Yes','SAR'),('SEN','Dakar','Yes','XOF'),('SRB','Yes','941','SRB'),('SYC','Victoria','Yes','SCR'),('SLE','Freetown','Yes','SLL'),('SGP','Singapore','Yes','SGD'),('SXM','Philipsburg','Part of NL','ANG'),('SVK','Bratislava','Yes','EUR'),('SVN','Ljubljana','Yes','EUR'),('SLB','Honiara','Yes','SBD'),('SOM','Mogadishu','Yes','SOS'),('ZAF','Pretoria','Yes','ZAR'),('SGS','Grytviken','Territory of GB',NULL),('KOR','Yes','410','KRW'),('SSD','Juba','Yes','SSP'),('ESP','Madrid','Yes','EUR'),('LKA','Colombo','Yes','LKR'),('BLM','Gustavia','Part of FR','EUR'),('SHN','Territory of GB','654','SHP'),('KNA','Basseterre','Yes','XCD'),('LCA','Castries','Yes','XCD'),('MAF','Marigot','Part of FR','EUR'),('SPM','Saint-Pierre','Part of FR','EUR'),('VCT','Kingstown','Yes','XCD'),('SDN','Khartoum','Yes','SDG'),('SUR','Paramaribo','Yes','SRD'),('SJM','Territory of NO','578',NULL),('SWZ','Mbabane','Yes','SZL'),('SWE','Stockholm','Yes','SEK'),('CHE','Bern','Yes','CHF'),('SYR','Damascus','Yes','SYP'),('STP','Sao Tome','Yes','STD'),('TWN','Taipei','Yes',NULL),('TJK','Dushanbe','Yes','TJS'),('TZA','Yes','834','TZS'),('THA','Bangkok','Yes','THB'),('TLS','Dili','Yes','USD'),('TGO','Lome','Yes','XOF'),('TKL',NULL,'Territory of NZ','NZD'),('TON','Nuku\'alofa','Yes','TOP'),('TTO','Port of Spain','Yes','TTD'),('TUN','Tunis','Yes','TND'),('TUR','Ankara','Yes','TRY'),('TKM','Ashgabat','Yes','TMT'),('TCA','Cockburn Town','Territory of GB','USD'),('TUV','Funafuti','Yes','AUD'),('UMI','MQ','KQ',NULL),('VIR','Charlotte Amalie','Territory of US','USD'),('GBR','Pound Sterling','2','UK'),('USA','Washington','Yes','USD'),('UGA','Kampala','Yes','UGX'),('UKR','Kiev','Yes','UAH'),('ARE','Abu Dhabi','Yes','AED'),('URY','Montevideo','Yes','UYU'),('UZB','Tashkent','Yes','UZS'),('VUT','Port Vila','Yes','VUV'),('VAT','Vatican City','Yes','EUR'),('VEN','Yes','937','VEF'),('VNM','Hanoi','Yes','VND'),('WLF','Mata Utu','Territory of FR','XPF'),('ESH','El-Aaiun','In contention','MAD'),('YEM','Sanaa','Yes','YER'),('ZMB','Lusaka','Yes','ZMW'),('ZWE','Harare','Yes','ZWL'),('ALA','Mariehamn','Part of FI','EUR'); 23 | /*!40000 ALTER TABLE `temp` ENABLE KEYS */; 24 | UNLOCK TABLES; 25 | 26 | -- Dump completed on 2019-09-29 19:51:07 27 | -------------------------------------------------------------------------------- /Chapter08/Activity8.01/back_CountryDetails.sql: -------------------------------------------------------------------------------- 1 | -- Table structure for table `temp` 2 | -- 3 | USE world_statistics; 4 | 5 | DROP TABLE IF EXISTS `temp`; 6 | /*!40101 SET @saved_cs_client = @@character_set_client */; 7 | /*!50503 SET character_set_client = utf8mb4 */; 8 | CREATE TABLE `temp` ( 9 | `Country Code` varchar(5) DEFAULT NULL, 10 | `Capital` varchar(50) DEFAULT NULL, 11 | `Is_Independent` varchar(25) DEFAULT NULL, 12 | `Currency` varchar(5) DEFAULT NULL 13 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 14 | /*!40101 SET character_set_client = @saved_cs_client */; 15 | 16 | -- 17 | -- Dumping data for table `temp` 18 | -- 19 | 20 | LOCK TABLES `temp` WRITE; 21 | /*!40000 ALTER TABLE `temp` DISABLE KEYS */; 22 | INSERT INTO `temp` VALUES ('AFG','Kabul','Yes','AFN'),('ALB','Tirana','Yes','ALL'),('DZA','Algiers','Yes','DZD'),('ASM','Pago Pago','Territory of US','USD'),('AND','Andorra la Vella','Yes','EUR'),('AGO','Luanda','Yes','AOA'),('AIA','The Valley','Territory of GB','XCD'),('ATA',NULL,'International',NULL),('ATG','St. John\'s','Yes','XCD'),('ARG','Buenos Aires','Yes','ARS'),('ARM','Yerevan','Yes','AMD'),('ABW','Oranjestad','Part of NL','AWG'),('AUS','Canberra','Yes','AUD'),('AUT','Vienna','Yes','EUR'),('AZE','Baku','Yes','AZN'),('BHS','Nassau','Yes','BSD'),('BHR','Manama','Yes','BHD'),('BGD','Dhaka','Yes','BDT'),('BRB','Bridgetown','Yes','BBD'),('BLR','Minsk','Yes','BYR'),('BEL','Brussels','Yes','EUR'),('BLZ','Belmopan','Yes','BZD'),('BEN','Porto-Novo','Yes','XOF'),('BMU','Hamilton','Territory of GB','BMD'),('BTN','Thimphu','Yes','INR'),('BOL','Yes','68','BOB'),('BIH','Sarajevo','Yes','BAM'),('BWA','Gaborone','Yes','BWP'),('BVT',NULL,'Territory of NO',NULL),('BRA','Brasilia','Yes','BRL'),('IOT','Diego Garcia','Territory of GB',NULL),('VGB','Road Town','Territory of GB','USD'),('BRN','Bandar Seri Begawan','Yes','BND'),('BGR','Sofia','Yes','BGN'),('BFA','Ouagadougou','Yes','XOF'),('BDI','Bujumbura','Yes','BIF'),('KHM','Phnom Penh','Yes','KHR'),('CMR','Yaounde','Yes','XAF'),('CAN','Ottawa','Yes','CAD'),('CPV','Praia','Yes','CVE'),('BQ','840','US Dollar','AHO'),('CYM','George Town','Territory of GB','KYD'),('CAF','Bangui','Yes','XAF'),('TCD','N\'Djamena','Yes','XAF'),('CHL','Santiago','Yes','CLP'),('CHN','Beijing','Yes','CNY'),('CXR','Flying Fish Cove','Territory of AU',NULL),('CCK','West Island','Territory of AU',NULL),('COL','Bogota','Yes','COP'),('COM','Moroni','Yes','KMF'),('COG','Brazzaville','Yes','XAF'),('COD','Kinshasa','Yes',NULL),('COK','Avarua','Associated with NZ','NZD'),('CRI','San Jose','Yes','CRC'),('HRV','Zagreb','Yes','HRK'),('CUB','Havana','Yes','CUP'),('CUW','Willemstad','Part of NL','ANG'),('CYP','Nicosia','Yes','EUR'),('CZE','Prague','Yes',NULL),('CIV','Yamoussoukro','Yes','XOF'),('DNK','Copenhagen','Yes','DKK'),('DJI','Djibouti','Yes','DJF'),('DMA','Roseau','Yes','XCD'),('DOM','214','Dominican Peso','72'),('ECU','Quito','Yes','USD'),('EGY','Cairo','Yes','EGP'),('SLV','San Salvador','Yes','USD'),('GNQ','Malabo','Yes','XAF'),('ERI','Asmara','Yes','ERN'),('EST','Tallinn','Yes','EUR'),('ETH','Addis Ababa','Yes','ETB'),('FLK','Stanley','Territory of GB','FKP'),('FRO','Torshavn','Part of DK',NULL),('FJI','Suva','Yes','FJD'),('FIN','Helsinki','Yes','EUR'),('FRA','Paris','Yes','EUR'),('GUF','Cayenne','Part of FR','EUR'),('PYF','Papeete','Territory of FR','XPF'),('ATF','Port-aux-Francais','Territory of FR',NULL),('GAB','Libreville','Yes','XAF'),('GMB','Banjul','Yes','GMD'),('GEO','Tbilisi','Yes','GEL'),('DEU','Berlin','Yes','EUR'),('GHA','Accra','Yes','GHS'),('GIB','Gibraltar','Territory of GB','GIP'),('GRC','Athens','Yes','EUR'),('GRL','Nuuk','Part of DK','DKK'),('GRD','St. George\'s','Yes','XCD'),('GLP','Basse-Terre','Part of FR','EUR'),('GUM','Hagatna','Territory of US','USD'),('GTM','Guatemala City','Yes','GTQ'),('GGY','St Peter Port','Crown dependency of GB','GBP'),('GIN','Conakry','Yes','GNF'),('GNB','Bissau','Yes','XOF'),('GUY','Georgetown','Yes','GYD'),('HTI','Port-au-Prince','Yes','USD'),('HMD',NULL,'Territory of AU',NULL),('HND','Tegucigalpa','Yes','HNL'),('HK','Part of CN',NULL,'HKG'),('HUN','Budapest','Yes','HUF'),('ISL','Reykjavik','Yes','ISK'),('IND','New Delhi','Yes','INR'),('IDN','Jakarta','Yes','IDR'),('IRN','Yes','364','IRR'),('IRQ','Baghdad','Yes','IQD'),('IRL','Dublin','Yes','EUR'),('IMN','Douglas','Crown dependency of GB','GBP'),('ISR','Jerusalem','Yes','ILS'),('ITA','Rome','Yes','EUR'),('JAM','Kingston','Yes','JMD'),('JPN','Tokyo','Yes','JPY'),('JEY','Saint Helier','Crown dependency of GB','GBP'),('JOR','Amman','Yes','JOD'),('KAZ','Astana','Yes','KZT'),('KEN','Nairobi','Yes','KES'),('KIR','Tarawa','Yes','AUD'),('KWT','Kuwait City','Yes','KWD'),('KGZ','Bishkek','Yes','KGS'),('LAO','Vientiane','Yes','LAK'),('LVA','Riga','Yes','EUR'),('LBN','Beirut','Yes','LBP'),('LSO','Maseru','Yes','ZAR'),('LBR','Monrovia','Yes','LRD'),('LBY','Tripoli','Yes','LYD'),('LIE','Vaduz','Yes','CHF'),('LTU','Vilnius','Yes','EUR'),('LUX','Luxembourg','Yes','EUR'),('MO','Part of CN','446','MAC'),('MKD','Yes','807','MKD'),('MDG','Antananarivo','Yes','MGA'),('MWI','Lilongwe','Yes','MWK'),('MYS','Kuala Lumpur','Yes','MYR'),('MDV','Male','Yes','MVR'),('MLI','Bamako','Yes','XOF'),('MLT','Valletta','Yes','EUR'),('MHL','Majuro','Yes','USD'),('MTQ','Fort-de-France','Part of FR','EUR'),('MRT','Nouakchott','Yes','MRO'),('MUS','Port Louis','Yes','MUR'),('MYT','Mamoudzou','Part of FR','EUR'),('MEX','Mexico City','Yes','MXN'),('FSM','Yes','840','USD'),('MDA','Yes','498','MDL'),('MCO','Monaco','Yes','EUR'),('MNG','Ulan Bator','Yes','MNT'),('MNE','Podgorica','Yes','EUR'),('MSR','Plymouth','Territory of GB','XCD'),('MAR','Rabat','Yes','MAD'),('MOZ','Maputo','Yes','MZN'),('MMR','Nay Pyi Taw','Yes','MMK'),('NAM','Windhoek','Yes','ZAR'),('NRU','Yaren','Yes','AUD'),('NPL','Kathmandu','Yes','NPR'),('NLD','Amsterdam','Yes','EUR'),('NCL','Noumea','Territory of FR','XPF'),('NZL','Wellington','Yes','NZD'),('NIC','Managua','Yes','NIO'),('NER','Niamey','Yes','XOF'),('NGA','Abuja','Yes','NGN'),('NIU','Alofi','Associated with NZ','NZD'),('NFK','Kingston','Territory of AU','AUD'),('PRK','Yes','408','KPW'),('MNP','Saipan','Commonwealth of US','USD'),('NOR','Oslo','Yes','NOK'),('OMN','Muscat','Yes','OMR'),('PAK','Islamabad','Yes','PKR'),('PLW','Melekeok','Yes','USD'),('PSE',NULL,'STATE OF\"','\"91'),('PAN','Panama City','Yes','USD'),('PNG','Port Moresby','Yes','PGK'),('PRY','Asuncion','Yes','PYG'),('PER','Lima','Yes','PEN'),('PHL','Manila','Yes','PHP'),('PCN','Adamstown','Territory of GB','NZD'),('POL','Warsaw','Yes','PLN'),('PRT','Lisbon','Yes','EUR'),('PRI','San Juan','Commonwealth of US','USD'),('QAT','Doha','Yes','QAR'),('ROU','Bucharest','Yes','RON'),('RUS','Moscow','Yes','RUB'),('RWA','Kigali','Yes','RWF'),('REU','Saint-Denis','Part of FR','EUR'),('WSM','Apia','Yes','WST'),('SMR','San Marino','Yes','EUR'),('SAU','Riyadh','Yes','SAR'),('SEN','Dakar','Yes','XOF'),('SRB','Yes','941','SRB'),('SYC','Victoria','Yes','SCR'),('SLE','Freetown','Yes','SLL'),('SGP','Singapore','Yes','SGD'),('SXM','Philipsburg','Part of NL','ANG'),('SVK','Bratislava','Yes','EUR'),('SVN','Ljubljana','Yes','EUR'),('SLB','Honiara','Yes','SBD'),('SOM','Mogadishu','Yes','SOS'),('ZAF','Pretoria','Yes','ZAR'),('SGS','Grytviken','Territory of GB',NULL),('KOR','Yes','410','KRW'),('SSD','Juba','Yes','SSP'),('ESP','Madrid','Yes','EUR'),('LKA','Colombo','Yes','LKR'),('BLM','Gustavia','Part of FR','EUR'),('SHN','Territory of GB','654','SHP'),('KNA','Basseterre','Yes','XCD'),('LCA','Castries','Yes','XCD'),('MAF','Marigot','Part of FR','EUR'),('SPM','Saint-Pierre','Part of FR','EUR'),('VCT','Kingstown','Yes','XCD'),('SDN','Khartoum','Yes','SDG'),('SUR','Paramaribo','Yes','SRD'),('SJM','Territory of NO','578',NULL),('SWZ','Mbabane','Yes','SZL'),('SWE','Stockholm','Yes','SEK'),('CHE','Bern','Yes','CHF'),('SYR','Damascus','Yes','SYP'),('STP','Sao Tome','Yes','STD'),('TWN','Taipei','Yes',NULL),('TJK','Dushanbe','Yes','TJS'),('TZA','Yes','834','TZS'),('THA','Bangkok','Yes','THB'),('TLS','Dili','Yes','USD'),('TGO','Lome','Yes','XOF'),('TKL',NULL,'Territory of NZ','NZD'),('TON','Nuku\'alofa','Yes','TOP'),('TTO','Port of Spain','Yes','TTD'),('TUN','Tunis','Yes','TND'),('TUR','Ankara','Yes','TRY'),('TKM','Ashgabat','Yes','TMT'),('TCA','Cockburn Town','Territory of GB','USD'),('TUV','Funafuti','Yes','AUD'),('UMI','MQ','KQ',NULL),('VIR','Charlotte Amalie','Territory of US','USD'),('GBR','Pound Sterling','2','UK'),('USA','Washington','Yes','USD'),('UGA','Kampala','Yes','UGX'),('UKR','Kiev','Yes','UAH'),('ARE','Abu Dhabi','Yes','AED'),('URY','Montevideo','Yes','UYU'),('UZB','Tashkent','Yes','UZS'),('VUT','Port Vila','Yes','VUV'),('VAT','Vatican City','Yes','EUR'),('VEN','Yes','937','VEF'),('VNM','Hanoi','Yes','VND'),('WLF','Mata Utu','Territory of FR','XPF'),('ESH','El-Aaiun','In contention','MAD'),('YEM','Sanaa','Yes','YER'),('ZMB','Lusaka','Yes','ZMW'),('ZWE','Harare','Yes','ZWL'),('ALA','Mariehamn','Part of FI','EUR'); 23 | /*!40000 ALTER TABLE `temp` ENABLE KEYS */; 24 | UNLOCK TABLES; 25 | /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; 26 | 27 | 28 | -- Dump completed on 2019-09-29 19:51:07 29 | -------------------------------------------------------------------------------- /Chapter08/Activity8.02/Activity_6_02_Solution_Populate_Tables.js: -------------------------------------------------------------------------------- 1 | var mysqlconnection = require("./mysqlconnection.js"); 2 | 3 | 4 | mysqlconnection.query("USE CustomerDatabase", function (err, result) { 5 | if (err) throw err.code; 6 | console.log(result); 7 | }); 8 | var record = [['Big Company'],['Little Company'],['Old Company'],['New Company']]; 9 | 10 | var sql = "INSERT INTO customers(CustomerName) VALUES ?;" 11 | 12 | mysqlconnection.query(sql, [record], function (err, result) { 13 | if (err) throw "Problem creating database" + err.code; 14 | console.log(result); 15 | }); 16 | 17 | record = [ 18 | [1,'SKU001','01-JAN-2020 09:10am',3], 19 | [2,'SKU001','01-JAN-2020 09:10am',2], 20 | [3,'SKU002','02-FEB-2020 09:15am',5], 21 | [4,'SKU003','05-MAY-2020 12:21pm',10], 22 | ]; 23 | var sql = "INSERT INTO CustomerPurchases(CustID,SKU,SalesDateTime,Quantity) VALUES ?;" 24 | 25 | mysqlconnection.query(sql, [record], function (err, result) { 26 | if (err) throw "Problem creating database" + err.code; 27 | console.log(result); 28 | process.exit(); 29 | }); 30 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.01/MySQLInsertOneRecord.js: -------------------------------------------------------------------------------- 1 | //This script inserts a single record into the new database table 2 | //You guessed it, include the connection module 3 | var mysqlconnection = require("./mysqlconnection.js"); 4 | 5 | //Create a query to insert the data 6 | //Notice we need to include the database name with the table, world_statistics.continents 7 | //This is because we did not specify a database in the connection, we'll get to this soon enough 8 | // 9 | //Also notice the question mark, also important 10 | var sql = "INSERT INTO world_statistics.continents (continent) VALUES ?"; 11 | 12 | //Create a record object, this is an array of data to insert into the table. We are creating a single dimension here 13 | var record = [[`Africa`]]; 14 | //Now we execute the SQL statement 15 | //The second parameter is the record object, it is in square brackets to indicate it is an array, albeit one dimension only 16 | //When the sql is executed, record will replace the question mark, Node.js knows to do this 17 | //Of course, error checking is included, as always 18 | mysqlconnection.query(sql, [record], function (err, result) { 19 | 20 | //Deal with the error should one occur 21 | if (err) throw "Problem inserting the data" + err. code; 22 | 23 | //Otherwise, log the results to the console so user can see what happened 24 | console.log(result); //This will report ALL result details 25 | console.log("Number of rows affected : " + result.affectedRows); //This will report only how many rows, should be 1 in this example 26 | console.log("New records ID : " + result.insertId); //Reports the ID of the new record...you can extract specific details 27 | 28 | //Exit script 29 | process.exit(); 30 | 31 | //Bracketing 32 | }); 33 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.02/MySQLInsertMultipleRecordsContinents.js: -------------------------------------------------------------------------------- 1 | //This script inserts a single record into the new database table 2 | //You guessed it, include the connection module 3 | var mysqlconnection = require("MySQLConnection.js"); 4 | 5 | //Create a query to insert the data 6 | //Notice we need to include the database name with the table, world_statistics.continents 7 | //This is because we did not specify a database in the connection, we'll get to this soon enough 8 | // 9 | //Also notice the question mark, also important 10 | var sql = "CREATE TABLE `world_statistics`.`userContinents` (\ 11 | `ContinentID` int(11) NOT NULL AUTO_INCREMENT, \ 12 | `Continent` varchar(13) DEFAULT NULL, \ 13 | PRIMARY KEY(`ContinentID`)\ 14 | );"; 15 | mysqlconnection.query(sql,function(err) { 16 | if (err) throw "Problem creating the table:- " + err.code; 17 | console.log("Table created"); 18 | }); 19 | 20 | var sql = "INSERT INTO world_statistics.userContinents (continent) VALUES ?"; 21 | 22 | //Create a record object, this is an array of data to insert into the table. We are creating a single dimension here 23 | var record = [['Asia'],['Europe'],['North America'],['Oceania']; 24 | 25 | 26 | //Now we execute the SQL statement 27 | //The second parameter is the record object, it is in square brackets to indicate it is an array, albeit one dimension only 28 | //When the sql is executed, record will replace the question mark, Node.js knows to do this 29 | //Of course, error checking is included, as always 30 | mysqlconnection.query(sql, [record], function (err, result) { 31 | 32 | //Deal with the error should one occur 33 | if (err) throw "Problem inserting the data" + err. code; 34 | 35 | //Otherwise, log the results to the console so user can see what happened 36 | console.log(result); //This will report ALL result details 37 | console.log("Number of rows affected : " + result.affectedRows); //This will report only how many rows, should be 1 in this example 38 | console.log("New records ID : " + result.insertId); //Reports the ID of the new record...you can extract specific details 39 | 40 | //Exit script 41 | process.exit(); 42 | 43 | //Bracketing 44 | }); 45 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.03/MySQLInsertMultipleFieldRecords.js: -------------------------------------------------------------------------------- 1 | var mysqlconnection = require("MySQLConnection.js"); 2 | var sql = "CREATE TABLE world_statistics.Region1(CountryID INT, `Country Code` VARCHAR(45));"; 3 | 4 | mysqlconnection.query(sql, function (err, result) { 5 | 6 | if (err) throw "Problem creatings the data" + err. code; 7 | 8 | console.log(result); 9 | console.log("Number of rows affected : " + result.affectedRows) 10 | console.log("New records ID : " + result.insertId); 11 | 12 | }); 13 | 14 | var records = "SELECT `ContinentID`, `Country Code` FROM world_statistics.countries WHERE `CountryID` < 10 ORDER BY `CountryID`"; 15 | var sql = "INSERT INTO world_statistics.country (`CountryID`,`Country Code`)"; 16 | sql = sql + " " + records; 17 | mysqlconnection.query(sql, function (err, result) { 18 | if (err) throw "Problem inserting the data" + err.code; 19 | console.log(result); 20 | console.log("Number of rows affected : " + result.affectedRows); 21 | console.log("New records ID : " + result.insertId); 22 | process.exit(); 23 | }); 24 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.04/UpdateOneRecord.js: -------------------------------------------------------------------------------- 1 | // :) Just do it 2 | var mysqlconnection = require("MySQLConnection.js"); 3 | 4 | //Instruct server to use world_statistics 5 | mysqlconnection.query("USE world_statistics", function (err) { 6 | if (err) throw err; 7 | 8 | console.log("Using world_statistics database"); 9 | 10 | //Resize the field so we can fit the new name in 11 | var ChangeCol = "ALTER TABLE `continents` " 12 | ChangeCol = ChangeCol + "CHANGE COLUMN `Continent` `Continent` VARCHAR(20) NULL DEFAULT NULL;" 13 | mysqlconnection.query(ChangeCol, function (err) { 14 | if (err) throw err; 15 | 16 | console.log("Column Continent has been resized"); 17 | 18 | //Set a variable for the new value and the ContinentID we are changing 19 | var updateValues = ["Australia/Oceana",5]; 20 | 21 | //Create the SQL 22 | var sql = "UPDATE continents SET Continent = ? WHERE ContinentID = ? "; 23 | 24 | //Execute it...don't forget errors 25 | mysqlconnection.query(sql, updateValues, function (err, result) { 26 | if (err) throw err; 27 | 28 | //Tell user we are finished 29 | console.log("Record has been updated"); 30 | 31 | //And leave 32 | process.exit(); 33 | 34 | //Close brackets for update 35 | }); 36 | }); 37 | }); 38 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.05/TotalPopulationByContinent.js: -------------------------------------------------------------------------------- 1 | //This script will extract some data, format it and put it to the browser when we get a request 2 | 3 | //Include modules for http and mysqlconnection 4 | var http = require('http'); 5 | var mysqlconnection = require("../mysqlconnection.js"); 6 | var numeral = require('numeral'); 7 | 8 | //We want to use the world_statistics database 9 | mysqlconnection.query("USE world_statistics"); 10 | 11 | //Prepare variables 12 | var FilterYear = ""; //Our filter for year 13 | var string = ""; //To build our output into 14 | var banner = ""; //Page banner 15 | var headings = ""; //Column headings 16 | var temp = ""; //for building output banner 17 | var sql = ""; //For the SQL statement 18 | var tablestyle = ""; //styling for the table 19 | 20 | 21 | //Build the SQL statement to extract the data 22 | var sql = "SELECT " 23 | sql = sql + " continents.Continent AS Continent_Region, " 24 | sql = sql + " Sum(countrypopulation.StatisticValue) AS `Total_Population`, " 25 | sql = sql + " countrypopulation.Year, " 26 | sql = sql + " Count(country.CountryID) AS `Total_Countries` " 27 | sql = sql + "FROM " 28 | sql = sql + " continents " 29 | sql = sql + " INNER JOIN country ON country.ContinentID = continents.ContinentID " 30 | sql = sql + " INNER JOIN countrypopulation ON countrypopulation.`Country Code` = country.`Country Code` " 31 | sql = sql + "WHERE " 32 | sql = sql + " countrypopulation.Year = ? " // ? so we can change the year easily 33 | sql = sql + "GROUP BY " 34 | sql = sql + " continents.Continent, " 35 | sql = sql + " countrypopulation.Year " 36 | sql = sql + "ORDER BY " 37 | sql = sql + " `Total_Population` DESC "; 38 | 39 | //Create the server to listen for requests 40 | http.createServer(function (req, res) { 41 | res.writeHead(200, {'Content-Type': 'text/html'}); 42 | 43 | //Prepare the variable values 44 | FilterYear = 2011; 45 | banner = "Continent Population " + FilterYear; 46 | headings = "Continent_RegionTotal PopulationTotal Countries"; 47 | 48 | //When a request is received, run the SQL with the filters 49 | //Check for errors, values returned go into the object named result 50 | mysqlconnection.query(sql, FilterYear, function (err, result) { 51 | if (err) throw err; 52 | 53 | //Now we have to prepare the data, make it look good for output 54 | //To line everything up we are going to put it into a table 55 | //It will all come together in the end 56 | 57 | //NEW COMMAND: for each record in result, put the record in the object named Statistics 58 | result.forEach(function(Statistics){ 59 | 60 | //Now the fun begins, format the output to make it look cool 61 | //We are going to build up the variable named string with each record 62 | //wrap each record in Table Row tags and each data point in table cell tags 63 | //wrap each data point in html code to format its size and color 64 | 65 | string = string + "" //Start table row 66 | 67 | //add the Continent 68 | string = string + "" + Statistics.Continent_Region + "" 69 | 70 | //add the Population Total 71 | string = string + "" + numeral(Statistics.Total_Population).format('0.00a') + "" 72 | 73 | //add the Total_Countries 74 | string = string + "" + Statistics.Total_Countries + "" 75 | 76 | string = string + "" //End table row 77 | 78 | //From here, it will loop around to the next record until there are no more records 79 | //Building a new row on each loop 80 | }); 81 | 82 | tablestyle = "" 83 | 84 | //Now we build the banner and headings into the variable temp 85 | temp = "" + banner + "
" 86 | temp = temp + "" 87 | temp = temp + "" + headings + "" 88 | 89 | //now we join them together 90 | string = tablestyle + temp + string + "
"; 91 | 92 | //And sent the lot back in response to the request 93 | res.end(string); 94 | 95 | //Bracketing for the SQL statement 96 | }); 97 | 98 | //Bracketing for the create server, tell it to listen on port 82 99 | }).listen(82); 100 | 101 | //Now we wait, when a response is received, the code will run, extract the data, build the output and send it 102 | -------------------------------------------------------------------------------- /Chapter08/mysqlconnection.js: -------------------------------------------------------------------------------- 1 | //This is the final incarnation of the mysqlconnection script 2 | //it is now a module that can be reused. 3 | //By setting this connection script up as a module, you only need to 4 | //put the connection details in here and NOT in other scripts 5 | //If the details change in the future, you only need to change them here, once, all other scripts 6 | //using the module will still connect, so much easier for maintenance 7 | 8 | 9 | //Include the sql2 module so we can connect to the database server 10 | var mysql = require('mysql'); 11 | 12 | //Create the connection 13 | var mysqlconnection = mysql.createConnection({ 14 | host: "", 15 | port: "3306", //This will usually be 3306 but can be changed on the server or if the server is on the internet 16 | user: "", 17 | password: "" 18 | }); 19 | 20 | 21 | //Start the Connection Block 22 | //Make the connection, include error checking 23 | mysqlconnection.connect(function(err) { 24 | 25 | //Test for an error and provide a suitable message and the code if one occurs 26 | if (err){ 27 | throw err; 28 | }else{ 29 | //No error so report to the console that connection was successful 30 | //This can be omitted 31 | console.log("Connected to MySQL!"); 32 | } 33 | process.exit(); 34 | 35 | //Close off the connection blocks bracketing 36 | }); 37 | 38 | //End the Connection Block 39 | 40 | -------------------------------------------------------------------------------- /Chapter09/Exercise9.01/MS Access Training Data.mdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter09/Exercise9.01/MS Access Training Data.mdb -------------------------------------------------------------------------------- /Chapter09/Exercise9.01/MySQL Training Database.accdt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter09/Exercise9.01/MySQL Training Database.accdt -------------------------------------------------------------------------------- /Chapter09/Exercise9.06/Convert ms_access_migration to UTF8.sql: -------------------------------------------------------------------------------- 1 | /*Set the default collation on the database schema*/ 2 | ALTER DATABASE `ms_access_migration` CHARACTER SET utf8mb4 COLLATE = utf8mb4_unicode_ci ; 3 | 4 | /*Set the default collation on the tables, using convert will also set it for the fields in each table*/ 5 | ALTER TABLE ms_access_migration.badbits CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ; 6 | ALTER TABLE ms_access_migration.capacityindicatorsstats CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ; 7 | ALTER TABLE ms_access_migration.country CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ; 8 | ALTER TABLE ms_access_migration.errorlog CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ; 9 | ALTER TABLE ms_access_migration.genderstats CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ; 10 | ALTER TABLE ms_access_migration.jobstats CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ; 11 | ALTER TABLE ms_access_migration.lookups CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ; 12 | ALTER TABLE ms_access_migration.series CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ; 13 | ALTER TABLE ms_access_migration.users CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ; -------------------------------------------------------------------------------- /Chapter09/Exercise9.06/Create Collation Conversion commands.sql: -------------------------------------------------------------------------------- 1 | ALTER DATABASE `ms_access_migration` CHARACTER SET utf8mb4 COLLATE = utf8mb4_unicode_ci ; 2 | 3 | SELECT CONCAT("ALTER TABLE ", TABLE_SCHEMA, '.', TABLE_NAME," CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ;") AS ExecuteTheString 4 | FROM INFORMATION_SCHEMA.TABLES 5 | WHERE TABLE_SCHEMA="ms_access_migration" 6 | AND TABLE_TYPE="BASE TABLE"; 7 | 8 | 9 | -------------------------------------------------------------------------------- /Chapter10/Activity10.01/Create Function fnCountGroups.sql: -------------------------------------------------------------------------------- 1 | 2 | USE ms_access_migration; 3 | 4 | DROP FUNCTION IF EXISTS `fnCountGroups`; 5 | 6 | DELIMITER // 7 | 8 | CREATE FUNCTION `fnCountGroups`() RETURNS long 9 | READS SQL DATA 10 | BEGIN 11 | 12 | DECLARE TheValue Long; 13 | SET TheValue = (SELECT Count(`Group`) AS RecCount FROM (SELECT DISTINCT series.Group FROM series ) AS `Alias`); 14 | RETURN(TheValue); 15 | 16 | END// 17 | 18 | DELIMITER ; 19 | -------------------------------------------------------------------------------- /Chapter10/Activity10.01/fnCountGroups.bas: -------------------------------------------------------------------------------- 1 | SQL = "SELECT fnCountGroups() as RecCount" 2 | Call CreatePassThrough(SQL, "CntGroups", True, False) 3 | Set RS = CurrentDb.OpenRecordset("CntGroups", dbOpenDynaset) 4 | RS.MoveFirst 5 | Me.cntGroups = RS.Fields("RecCount") 6 | RS.Close -------------------------------------------------------------------------------- /Chapter10/Activity10.02/Create Function fnCountGroups.sql: -------------------------------------------------------------------------------- 1 | 2 | USE ms_access_migration; 3 | 4 | DROP FUNCTION IF EXISTS `fnCountGroups`; 5 | 6 | DELIMITER // 7 | 8 | CREATE FUNCTION `fnCountGroups`() RETURNS long 9 | READS SQL DATA 10 | BEGIN 11 | 12 | DECLARE TheValue Long; 13 | SET TheValue = (SELECT Count(`Group`) AS RecCount FROM (SELECT DISTINCT series.Group FROM series ) AS `Alias`); 14 | RETURN(TheValue); 15 | 16 | END// 17 | 18 | DELIMITER ; 19 | -------------------------------------------------------------------------------- /Chapter10/Activity10.02/Create Function fnCountSeries.sql: -------------------------------------------------------------------------------- 1 | USE ms_access_migration; 2 | 3 | DROP FUNCTION IF EXISTS `fnCountSeries`; 4 | 5 | DELIMITER // 6 | 7 | CREATE FUNCTION `fnCountSeries`() RETURNS long 8 | DETERMINISTIC 9 | BEGIN 10 | 11 | DECLARE TheValue Long; 12 | SET TheValue = (SELECT COUNT(*) FROM series); 13 | RETURN(TheValue); 14 | 15 | END// 16 | 17 | DELIMITER ; -------------------------------------------------------------------------------- /Chapter10/Activity10.03/Create Procedure spCountryList.sql: -------------------------------------------------------------------------------- 1 | 2 | USE ms_access_migration; 3 | 4 | DROP PROCEDURE IF EXISTS spCountryList; 5 | 6 | DELIMITER // 7 | 8 | CREATE PROCEDURE spCountryList() 9 | BEGIN 10 | 11 | SELECT DISTINCT country.`Country Code`, country.`Country Name` 12 | FROM country 13 | ORDER BY country.`Country Name`; 14 | 15 | END// 16 | 17 | DELIMITER ; 18 | -------------------------------------------------------------------------------- /Chapter10/Activity10.03/Create Procedure spGroupsList.sql: -------------------------------------------------------------------------------- 1 | USE ms_access_migration; 2 | 3 | DROP PROCEDURE IF EXISTS spGroupsList; 4 | 5 | DELIMITER // 6 | 7 | CREATE PROCEDURE spGroupsList() 8 | BEGIN 9 | 10 | SELECT DISTINCT series.Group 11 | FROM series 12 | ORDER BY series.Group; 13 | 14 | END// 15 | 16 | DELIMITER ; 17 | -------------------------------------------------------------------------------- /Chapter10/Activity10.03/spGroupsList and spCountryList.bas: -------------------------------------------------------------------------------- 1 | SQL = "Call spGroupsList;" 2 | Call CreatePassThrough(SQL, "spGroupsList", True, False) 3 | Me.cmbGroups.RowSource = "spGroupsList" 4 | 5 | SQL = "Call spCountryList;" 6 | Call CreatePassThrough(SQL, "spCountryList", True, False) 7 | Me.cmbCountry.RowSource = "spCountryList" -------------------------------------------------------------------------------- /Chapter10/Activity10.04/Solution The Parameterized Stored Procedure – Series List.bas: -------------------------------------------------------------------------------- 1 | SQL = "Call spSeriesList_par('" & Me.cmbGroups & "');" 2 | 3 | Call CreatePassThrough(SQL, "spSeriesFiltered", True, False) 4 | 5 | Me.cmbSeries.RowSource = "spSeriesFiltered" 6 | -------------------------------------------------------------------------------- /Chapter10/Activity10.05/Create Procedure spCountryList_par.sql: -------------------------------------------------------------------------------- 1 | 2 | USE ms_access_migration; 3 | DROP PROCEDURE IF EXISTS spCountryList_par; 4 | DELIMITER // 5 | 6 | CREATE PROCEDURE spCountryList_par(IN TableName VARCHAR(25), IN TheSeries VARCHAR(25) ) 7 | BEGIN 8 | 9 | SET @t1 = CONCAT( 10 | 'SELECT DISTINCT country.`Country Code`, country.`Country Name`, ' , TableName , '.`Series Code` ', 11 | 'FROM country INNER JOIN ' , TableName , ' ON country.`Country Code` = ' , TableName , '.`Country Code` ', 12 | 'WHERE ' , TableName , '.`Series Code` = "' , TheSeries , '" ', 13 | 'ORDER BY country.`Country Name`' 14 | ); 15 | 16 | PREPARE stmt1 FROM @t1; 17 | EXECUTE stmt1; 18 | DEALLOCATE PREPARE stmt1; 19 | 20 | END// 21 | 22 | DELIMITER ; -------------------------------------------------------------------------------- /Chapter10/Activity10.05/Create Procedure spDateRange_par.sql: -------------------------------------------------------------------------------- 1 | USE ms_access_migration; 2 | DROP PROCEDURE IF EXISTS spDateRange_par; 3 | DELIMITER // 4 | 5 | CREATE PROCEDURE spDateRange_par(IN TableName VARCHAR(25), IN TheSeries VARCHAR(25) ) 6 | BEGIN 7 | 8 | SET @t1 = CONCAT( 9 | 'SELECT DISTINCT ' , TableName , '.Year ', 10 | 'FROM ', TableName , ' ', 11 | 'WHERE ' , TableName , '.`Series Code` = "' , TheSeries , '" ', 12 | 'ORDER BY ', TableName ,'.Year' 13 | ); 14 | 15 | PREPARE stmt1 FROM @t1; 16 | EXECUTE stmt1; 17 | DEALLOCATE PREPARE stmt1; 18 | 19 | END// 20 | 21 | DELIMITER ; -------------------------------------------------------------------------------- /Chapter10/Activity10.05/spDateRange_par.bas: -------------------------------------------------------------------------------- 1 | SQL = "Call spDateRange_par('" & TableName & "','" & Me.cmbSeries & "');" 2 | Call CreatePassThrough(SQL, "spDateRange_par", True, False) 3 | 4 | 5 | 'Fill the Year dropdowns 6 | Me.StartYear.RowSource = "spDateRange_par" 7 | Me.StartYear = Me.StartYear.ItemData(0) 8 | 9 | Me.EndYear.RowSource = "spDateRange_par" 10 | Me.EndYear = Me.EndYear.ItemData(Me.EndYear.ListCount - 1) 11 | 12 | -------------------------------------------------------------------------------- /Chapter10/Exercise10.02/Create Function fnCountSeries.sql: -------------------------------------------------------------------------------- 1 | USE ms_access_migration; 2 | 3 | DROP FUNCTION IF EXISTS `fnCountSeries`; 4 | 5 | DELIMITER // 6 | 7 | CREATE FUNCTION `fnCountSeries`() RETURNS long 8 | DETERMINISTIC 9 | BEGIN 10 | 11 | DECLARE TheValue Long; 12 | SET TheValue = (SELECT COUNT(*) FROM series); 13 | RETURN(TheValue); 14 | 15 | END// 16 | 17 | DELIMITER ; -------------------------------------------------------------------------------- /Chapter10/Exercise10.03/Create Procedure spSeriesList.sql: -------------------------------------------------------------------------------- 1 | 2 | USE ms_access_migration; 3 | 4 | DROP PROCEDURE IF EXISTS spSeriesList; 5 | 6 | DELIMITER // 7 | 8 | CREATE PROCEDURE spSeriesList() 9 | BEGIN 10 | 11 | SELECT DISTINCT ms_access_migration.series.`Series Code`, ms_access_migration.series.`series Name` 12 | FROM ms_access_migration.series 13 | ORDER BY ms_access_migration.series.`series Name`; 14 | 15 | END// 16 | 17 | DELIMITER ; 18 | 19 | -------------------------------------------------------------------------------- /Chapter10/Exercise10.04/Create Procedure spSeriesList_par.sql: -------------------------------------------------------------------------------- 1 | 2 | USE ms_access_migration; 3 | 4 | DROP PROCEDURE IF EXISTS spSeriesList_par; 5 | 6 | DELIMITER // 7 | 8 | CREATE PROCEDURE spSeriesList_par(IN GroupName VARCHAR(25)) 9 | BEGIN 10 | 11 | SELECT DISTINCT ms_access_migration.series.`Series Code`, ms_access_migration.series.`series Name` 12 | FROM ms_access_migration.series 13 | WHERE series.`Group` = GroupName 14 | ORDER BY ms_access_migration.series.`series Name`; 15 | 16 | END// 17 | 18 | DELIMITER ; 19 | 20 | -------------------------------------------------------------------------------- /Chapter10/Exercise10.05/CONCAT sample.bas: -------------------------------------------------------------------------------- 1 | SELECT CONCAT('This ','is ','an ', 'example ','of ','string ','CONCATenation') -------------------------------------------------------------------------------- /Chapter10/Exercise10.05/Create Procedure spCountryList_par.sql: -------------------------------------------------------------------------------- 1 | 2 | USE ms_access_migration; 3 | DROP PROCEDURE IF EXISTS spCountryList_par; 4 | DELIMITER // 5 | 6 | CREATE PROCEDURE spCountryList_par(IN TableName VARCHAR(25), IN TheSeries VARCHAR(25) ) 7 | BEGIN 8 | 9 | SET @t1 = CONCAT( 10 | 'SELECT DISTINCT Country.`Country Code`, Country.`Country Name`, ' , TableName , '.`Series Code` ', 11 | 'FROM country INNER JOIN ' , TableName , ' ON country.`Country Code` = ' , TableName , '.`Country Code` ', 12 | 'WHERE ' , TableName , '.`Series Code` = "' , TheSeries , '" ', 13 | 'ORDER BY country.`Country Name`' 14 | ); 15 | 16 | PREPARE stmt1 FROM @t1; 17 | EXECUTE stmt1; 18 | DEALLOCATE PREPARE stmt1; 19 | 20 | END// 21 | 22 | DELIMITER ; -------------------------------------------------------------------------------- /Chapter10/Exercise10.05/Exercise 8_05 SELECT Case.bas: -------------------------------------------------------------------------------- 1 | Select Case Me.cmbGroups 2 | Case "Capacity Indicators" 3 | TableName = "capacityindicatorsstats" 4 | Case "Gender Statistics" 5 | TableName = "genderstats" 6 | Case "Job Statistics" 7 | TableName = "jobstats" 8 | End Select 9 | -------------------------------------------------------------------------------- /Chapter10/Exercise10.05/Final VBA Code to run the procedure.bas: -------------------------------------------------------------------------------- 1 | SQL = "Call spCountryList_par('" & TableName & "','" & Me.cmbSeries & "')" 2 | Call CreatePassThrough(SQL, "spCountryList_par", True, False) 3 | Me.cmbCountry.RowSource = "spCountryList_par" 4 | -------------------------------------------------------------------------------- /Chapter10/Exercise10.05/Test spCountryList.bas: -------------------------------------------------------------------------------- 1 | call spCountryList_par("Jobstats","FP.CPI.TOTL") -------------------------------------------------------------------------------- /Chapter10/Exercise10.06/Create Procedure spCTSource_par.sql: -------------------------------------------------------------------------------- 1 | USE ms_access_migration; 2 | DROP PROCEDURE IF EXISTS spCTSource_par; 3 | DELIMITER // 4 | 5 | 6 | CREATE PROCEDURE spCTSource_par 7 | ( 8 | IN TableName VARCHAR(25), 9 | IN TheSeries VARCHAR(25), 10 | IN TheGroup VARCHAR(25), 11 | IN TheCountry VARCHAR(100), 12 | IN StartYear VARCHAR(20), 13 | IN EndYear VARCHAR(20) 14 | ) 15 | 16 | 17 | BEGIN 18 | SET @t1 = CONCAT( 19 | 20 | 21 | 'SELECT country.`Country Name`, series.`Series Name`, ', TableName ,'.`Year`, ', TableName ,'.`StatisticValue` ' 22 | 'FROM (', TableName ,' ' 23 | 'INNER JOIN country ON ', TableName ,'.`Country Code` = country.`Country Code`) ' 24 | 'INNER JOIN series ON ', TableName ,'.`Series Code` = series.`Series Code` ' 25 | 'WHERE (((country.`Country Code`) = "' , TheCountry , '") ' 26 | 'And ((series.`Series Code`) = "' , TheSeries , '") ' 27 | 'And ((', TableName ,'.Year) >= "' , StartYear , '" ' 28 | 'And (', TableName ,'.Year) <= "' , EndYear , '") ' 29 | 'And ((series.Group) = "' , TheGroup , '"))' 30 | 'GROUP BY country.`Country Name`, series.`Series Name`, ', TableName ,'.`Year` ' 31 | 32 | 'ORDER BY ', TableName ,'.Year ' 33 | ); 34 | 35 | PREPARE stmt1 FROM @t1; 36 | EXECUTE stmt1; 37 | DEALLOCATE PREPARE stmt1; 38 | END// 39 | DELIMITER ; 40 | -------------------------------------------------------------------------------- /Chapter10/Exercise10.07/Exercise 8_07_10.bas: -------------------------------------------------------------------------------- 1 | UPDATE ms_access_migration.badbits SET badbits.BitField1 = 0 2 | WHERE badbits.BitField1 Is Null; 3 | 4 | UPDATE ms_access_migration.badbits SET badbits.BitField2 = 0 5 | WHERE badbits.BitField2 Is Null; 6 | -------------------------------------------------------------------------------- /Chapter11/Activity11.01/Global Connection VBA.bas: -------------------------------------------------------------------------------- 1 | 'Global Connection Variables 2 | Public g_Conn_DSNless As ADODB.Connection 3 | 4 | Public g_Conn_ODBC As ADODB.Connection -------------------------------------------------------------------------------- /Chapter11/Activity11.02/Solution for Activity – Artist_Units_Sold.bas: -------------------------------------------------------------------------------- 1 | 'This code is to go into the MySQLDatabase module 2 | 3 | 'Solution for Activity – Artist_Units_Sold 4 | 5 | Public Function ReadArtistSales() As Boolean 6 | 7 | 'Declare the variables to use 8 | Dim SQL As String 'To store the SQL statement 9 | Dim RS As Recordset 'The Recordset variable 10 | Dim Msg As String 'To display messages 11 | Dim Counter As Integer 'A counter 12 | Dim MyNamedRng As Range ' A range variable 13 | 14 | 'Setup error handling 15 | On Error GoTo HandleError 16 | 17 | '2. Prepare the SQL statement. Using a pre-prepared View has reduced the SQL statement to a single line 18 | 19 | 'Build the SQL statement to read from the two databases 20 | SQL = "" 21 | SQL = SQL & "SELECT * FROM vw_artist_unit_sales;" 22 | 23 | '3. Create the connection passing in the global connection variable and test if it was successful 24 | 25 | 'Make the connection to the server, test if it was successful 26 | If ConnectDB_DSNless(g_Conn_DSNless) = True Then 27 | 'Connection succeeded so we can continue processing 28 | 29 | '4. If successful, set the RecordSet variable RS and then open it with the SQL and connection 30 | 31 | 'Set the recordset variable 32 | Set RS = New ADODB.Recordset 33 | 34 | 'Load the recordset, pass in the SQL and the connection to use 35 | RS.Open SQL, g_Conn_DSNless 36 | 37 | '5. Test there are records and handle it appropriately if there are none 38 | 39 | 'Test there are records. 40 | If RS.EOF And RS.BOF Then 41 | 'No data, close the recordset 42 | RS.Close 43 | Set RS = Nothing 44 | 45 | 'tell user and then leave the function 46 | Msg = "There is no data" 47 | MsgBox Msg, vbOKOnly + vbInformation, "No data to display" 48 | Exit Function 49 | 50 | '6. Start processing the recordset if there are records, beginning with the headings. The starting column has changed to 3 “C” 51 | 52 | Else 53 | 'Insert Field headings for column headings 54 | For Counter = 0 To RS.Fields.Count - 1 55 | Worksheets("Data Sheet").Cells(1, 3 + Counter) = RS.Fields(Counter).Name 56 | Next 57 | 58 | '7. Place the data on the worksheet, and the column is now 3 59 | 60 | 'Place the data on the worksheet 61 | Worksheets("Data Sheet").Cells(2, 3).CopyFromRecordset RS 62 | 63 | '8. Set the range, the range is now on columns C and D, and the ranges name has been set to appropriately describe the ranges purpose 64 | 65 | 'Set and create a named range covering the columns with the Artist name and sales data only 66 | Set MyNamedRng = Worksheets("Data Sheet").Range("C2:D" & RS.RecordCount + 1) 67 | ActiveWorkbook.Names.Add Name:="Artist_Units_Sold", RefersTo:=MyNamedRng 68 | 69 | '9. Close the recordset and connection 70 | 71 | 'Close the recordset 72 | RS.Close 73 | Set RS = Nothing 74 | 75 | 'Close the connection 76 | g_Conn_DSNless.Close 77 | Set g_Conn_DSNless = Nothing 78 | 79 | '10. The result passed back is assigned to the function name 80 | 81 | 'Pass back success 82 | ReadArtistSales = True 83 | End If 84 | 85 | Else 86 | 'The connection routine will have displayed a message so nothing to do but leave 87 | ReadArtistSales = False 88 | End If 89 | 90 | '11. Set an exit point for error handling 91 | 92 | LeaveFunction: 93 | 'Leave the function 94 | Exit Function 95 | 96 | '12. Set error handling 97 | 98 | HandleError: 99 | 'Pass back Failed 100 | ReadArtistSales = False 101 | Resume LeaveFunction 102 | 103 | '13. And we are finished 104 | 105 | End Function 106 | -------------------------------------------------------------------------------- /Chapter11/Activity11.03/Solution for Activity – Artist Dropdown.bas: -------------------------------------------------------------------------------- 1 | 'NOTE: The code marked NEW CODE below is meant to be placed after the EXISTING CODE in the ReadArtistSales() function located in the MySQLDatabase Module 2 | ' The EXISTING CODE is here to provide you with a reference, it should not be duplicated in the function. 3 | 4 | 5 | 'Solution for Activity – Artist Dropdown 6 | 7 | 8 | '1. ReadArtistSales VBA modification 9 | ' Step 8 in the solution for the previous activity will now be 10 | 11 | 'EXISTING CODE 12 | 'Set and create a named range covering the columns with the Artist name and sales data only 13 | Set MyNamedRng = Worksheets("Data Sheet").Range("C2:D" & RS.RecordCount + 1) 14 | ActiveWorkbook.Names.Add Name:="Artist_Units_Sold", RefersTo:=MyNamedRng 15 | 16 | 'NEW CODE 17 | 'Set and create a named range covering the single column for the Artists name, data only 18 | Set MyNamedRng = Worksheets("Data Sheet").Range("C2:C" & RS.RecordCount + 1) 19 | ActiveWorkbook.Names.Add Name:="Artist_List", RefersTo:=MyNamedRng 20 | -------------------------------------------------------------------------------- /Chapter11/Activity11.04/Solution for Activity – Create Chart – Artist Trac.bas: -------------------------------------------------------------------------------- 1 | 'This code is to go into the Dashboard worksheets General section 2 | 3 | 4 | 'Solution for Activity – Create Chart – Artist Track Sales 5 | 6 | Private Sub ArtistTrackSales(ByVal pArtist As String) 7 | 8 | Dim RS As Recordset 9 | Dim SQL As String 10 | Dim MyNamedRng As Range 11 | 12 | 'Clear the target area first 13 | On Error Resume Next 14 | Worksheets("Data Sheet").Range("ArtistTrackSales").ClearContents 15 | On Error GoTo HandleError 16 | 17 | If ConnectDB_DSNless(g_Conn_DSNless) = True Then 18 | 'Prepare the SQL 19 | SQL = "" 20 | SQL = SQL & "SELECT TrackName, `Units Sold` " 21 | SQL = SQL & "FROM vw_artist_track_sales " 22 | SQL = SQL & "WHERE Name = '" & pArtist & "' " 23 | SQL = SQL & "ORDER BY `Units Sold` DESC" 24 | 25 | 'Set the recordset variable 26 | Set RS = New ADODB.Recordset 27 | 28 | 'Load the recordset, pass in the SQL and the connection to use 29 | RS.Open SQL, g_Conn_DSNless 30 | 31 | 'Test there are records. 32 | If RS.EOF And RS.BOF Then 33 | 'No data 34 | Exit Sub 35 | Else 36 | 'We have data so load it 37 | Worksheets("Data Sheet").Cells(2, 12).CopyFromRecordset RS 38 | 39 | 'Set and create a named range covering the column with the Genre name, data only 40 | Set MyNamedRng = Worksheets("Data Sheet").Range("L2:M" & RS.RecordCount + 1) 41 | ActiveWorkbook.Names.Add Name:="ArtistTrackSales", RefersTo:=MyNamedRng 42 | 43 | End If 44 | Else 45 | 'This line will be reached if there is no data, we do nothing and drop through 46 | End If 47 | Leavesub: 48 | 'Close recordset 49 | RS.Close 50 | Set RS = Nothing 51 | Exit Sub 52 | HandleError: 53 | MsgBox Err & " " & Error(Err) 54 | Resume Leavesub 55 | End Sub 56 | -------------------------------------------------------------------------------- /Chapter11/Exercise11.08/Exercise – Creating a Connection Function.bas: -------------------------------------------------------------------------------- 1 | 'This code is to go into the MySQLDatabase module 2 | 3 | 4 | 'Exercise – Creating a Connection Function 5 | '1. Continuing in the MySQLDatabase module, enter the following line after the variable declarations 6 | 7 | Public Function ConnectDB_DSNless(oConn As ADODB.Connection) As Boolean 8 | 9 | 'Note: VBA will add the End Function statement, be sure to add all of the following commands between the functions declaration and End Function. It will also add a line immediately under variable 'declarations, these lines will be added between functions and subs, they provide an easy way to see where the functions begin and end, especially when you scroll up and down the code 10 | '2. Add some comments on what the function does. This is for your benefit to jog the memory and for other developers who may need to modify the code at a later stage 11 | 'This Function will create a DSNless connection and assign it to the 12 | 'input variable. 13 | ' 14 | 'Input: oConn, ADODB.Connection variable to assign the connection to 15 | 'Output: Boolean, Success (True) or Failure (False) 16 | 17 | 3. Add and error handler instruction and declare some variables to use 18 | 19 | On Error GoTo HandleError 20 | 21 | 'Declare the variables we will use 22 | Dim Msg As String 23 | Dim str As String 24 | 25 | '4. Set the connection variable to a new variable, until now it has just been a declaration, this will set it as an actual connection type 26 | 27 | 'Set the passed in connection variable to a new connection 28 | Set oConn = New ADODB.Connection 29 | 30 | 'Use the Client cursor so we can read the number of records returned 31 | oConn.CursorLocation = adUseClient 32 | 33 | '5. Enter the following lines, as in previous chapters, fill in your specific details for ServerIP, User and Password. Be sure to take out the <> as well. Note that each of the parameters are separated by 'a semi-colon and no spaces. 34 | 35 | 'Prepare the connection string 36 | str = "DRIVER={MySQL ODBC 5.3 Unicode Driver};" 37 | str = str & "SERVER=;" 38 | str = str & "PORT=3306;" 39 | str = str & "DATABASE=;" 40 | str = str & "UID=;" 41 | str = str & "PWD=;" 42 | str = str & "Option=3" 43 | 44 | 45 | 'Note: Option=3 is a server directive. It is optional however leaving it out could cause issues with reading the data on some databases. If you do leave it out, be sure to remove the Semi-colon from the 'previous statement 46 | '6. Now open the connection. If there is an error, the code will jump to the error handler as defined earlier in the code, otherwise it will continue with the next statement 47 | 48 | 'Open the connection, if there is a problem, it will happen here 49 | oConn.Open str 50 | 51 | '7. If the connection was made, then we will get to here, pass back a True, so the calling routine knows the connection was successful 52 | 'No problem, good, pass back a True to signify connection was successful 53 | 54 | ConnectDB_DSNless = True 55 | 56 | '8. Declare a sub routine to exit the function, and the error handler will then have a point to resume to to exit the function. Immediately followed by an actual Exit Function. At this point the Function 'will terminate. 57 | 58 | LeaveFunction: 59 | 'and leave 60 | Exit Function 61 | 62 | '9. Declare the errorHandler sub routine to handle any errors, in here we are preparing a message to the user with the error number and description included and displaying it. 63 | 64 | HandleError: 65 | 66 | 'There was a problem, tell the user and include the error number and message 67 | Msg = "There was an error - " & Err & " - " & Error(Err) 68 | MsgBox Msg, vbOKOnly + vbCritical, "Problem Connecting to server" 69 | 70 | '10. After the user has clicked OK, pass back a False to the calling routine to indicate failure to connect then resume code at the LeaveFunction sub routine to exit. The End Function will already be 'there, don’t put it in twice. 71 | 'Pass back a False to signify there was an issue to the calling code 72 | ConnectDB_DSNless = False 73 | 74 | 'Leave the function 75 | Resume LeaveFunction 76 | 77 | End Function 78 | -------------------------------------------------------------------------------- /Chapter11/Exercise11.09/Exercise – Read Genre Sales.bas: -------------------------------------------------------------------------------- 1 | 'This code is to go into the MySQLDatabase module 2 | 3 | 'Exercise – Read Genre Sales 4 | 5 | '1. Continuing with the MySQLDatabase function 6 | '2. Declare the function and enter comments on the what the function is doing 7 | 8 | Public Function ReadGenreSales () as Boolean 9 | 'This function will read Genre Sales data from the MySQL database 10 | 'It will place the data in the worksheet named 'Data Sheet' 11 | 'It will cycle through the Field headings and use them for column headings in Row 1 12 | 'It will then place the data starting at Row 2 13 | 14 | '3. Declare the variables and setup error handling 15 | 16 | 'Declare the variables to use 17 | Dim SQL As String 'To store the SQL statement 18 | Dim RS As Recordset 'The Recordset variable 19 | Dim Msg As String 'To display messages 20 | Dim Counter As Integer 'A counter 21 | Dim MyNamedRng As Range ' A range variable 22 | 23 | 'Setup error handling 24 | On Error GoTo HandleError 25 | 26 | '4. Build the SQL statement to read the data 27 | 28 | 'Build the SQL statement to read from the two databases 29 | SQL = "" 30 | SQL = SQL & "SELECT " 31 | SQL = SQL & "genre.Name, " 32 | SQL = SQL & "Sum(invoiceline.Quantity) AS `Units Sold` " 33 | SQL = SQL & "FROM " 34 | SQL = SQL & "genre " 35 | SQL = SQL & "INNER JOIN track ON track.GenreId = genre.GenreId " 36 | SQL = SQL & "LEFT JOIN invoiceline ON invoiceline.TrackId = track.TrackId " 37 | SQL = SQL & "Group BY " 38 | SQL = SQL & "genre.Name " 39 | SQL = SQL & "Order BY " 40 | SQL = SQL & "genre.Name" 41 | 42 | '5. Connect to the server and test it worked 43 | 44 | 'Make the connection to the server, test if it was successful 45 | If ConnectDB_DSNless(g_Conn_DSNless) = True Then 46 | 'Connection succeeded so we can continue processing 47 | 48 | '6. The connection worked so setup the recordset 49 | 50 | 'Set the recordset variable 51 | Set RS = New ADODB.Recordset 52 | 53 | '7. Load the recordset using the SQL and connection 54 | 55 | 'Load the recordset, pass in the SQL and the connection to use 56 | RS.Open SQL, g_Conn_DSNless 57 | 58 | '8. Test there are records to work with 59 | 60 | 'Test there are records. 61 | 'A recordset can only be at End Of File and Beginning Of File at the same time when the recordset is empty 62 | If RS.EOF And RS.BOF Then 63 | 64 | '9. If execution gets in here then there are no records, we need to deal with this situation by telling the user, closing the recordset and leaving the function 65 | 66 | 'No data, close the recordset 67 | RS.Close 68 | Set RS = Nothing 69 | 70 | 'tell user and then leave the function 71 | Msg = "There is no data" 72 | MsgBox Msg, vbOKOnly + vbInformation, "No data to display" 73 | Exit Function 74 | 75 | '10. If we get into this part the record test, happy days, we have data so we need to process it 76 | 77 | Else 78 | 'We have data 79 | 80 | '11. We need headings for the data on the worksheet, so for this exercise, we will use the field names. 81 | 82 | 'Insert Field headings for column headings 83 | 'We cycle through the field collection 84 | For Counter = 0 To RS.Fields.Count - 1 85 | 'Put the fieldname in the cell on row 1 86 | 'When cycling through objects or data, it is easier to refer to the worksheet cells by their numeric values 87 | Cells(1, 1 + Counter) = RS.Fields(Counter).Name 88 | Next 89 | 90 | '12. We are done adding the headings, now to add the data. In Excel, we can use the CopyFromRecordset command to copy the entire dataset with one command, too easy 91 | 92 | 'Starting at cell in Row 2, Column 1, copy the entire recordset into the worksheet 93 | Worksheets("Data Sheet").Cells(2, 1).CopyFromRecordset RS 94 | 95 | '13. Set a named range for the data, we use the RS.RecordCount value to calculate how many rows the range should cover 96 | 97 | 'Set and create a named range covering the column with the Genre name, data only 98 | Set MyNamedRng = Worksheets("Data Sheet").Range("A2:A" & RS.RecordCount + 1) 99 | ActiveWorkbook.Names.Add Name:="Genre", RefersTo:=MyNamedRng 100 | 101 | '14. Now we have our data in place, start closing everything down 102 | 103 | 'Close the recordset 104 | RS.Close 105 | Set RS = Nothing 106 | 107 | 'Close the connection 108 | g_Conn_DSNless.Close 109 | Set g_Conn_DSNless = Nothing 110 | 111 | '15. And pass back success 112 | 113 | 'Pass back success 114 | ReadGenreSales = True 115 | End If 116 | 117 | '16. If we get in here after the connection test, then the connection failed so leave the function 118 | 119 | Else 120 | 'Connection failed if gets in here, just drop through to leave 121 | 'The connection routine will have displayed a message so nothing to do but leave 122 | ReadGenreSales = False 123 | Exit Function 124 | End If 125 | 126 | '17. And leave the function 127 | 128 | LeaveFunction: 129 | 'Leave the function 130 | Exit Function 131 | 132 | '18. But if we get in here, we have had an error 133 | 134 | HandleError: 135 | 'In this sample we are just going to display the error and leave the function 136 | 'you may want to log the error or do something else 137 | 'depending on your requirements 138 | MsgBox Err & "-" & Error(Err), vbOKOnly + vbCritical, "There was an error" 139 | 140 | '19. Pass back a fail  and leave the function 141 | 142 | 'Pass back Failed 143 | ReadGenreSales = False 144 | Resume LeaveFunction 145 | 146 | '20. Of course, the End Function has been here all along 147 | 148 | End Function 149 | -------------------------------------------------------------------------------- /Chapter11/Exercise11.11/Workbook_Opoen Code.bas: -------------------------------------------------------------------------------- 1 | Private Sub Workbook_Open() 2 | 'Load the intial data 3 | ReadGenreSales 4 | ReadArtistSales 5 | End Sub 6 | -------------------------------------------------------------------------------- /Chapter11/Exercise11.12/Exercise – Load Genre Sales Chart Data.bas: -------------------------------------------------------------------------------- 1 | 'This code is to go into the Dashboard worksheets General section 2 | 3 | 'Exercise – Load Genre Sales Chart Data 4 | 5 | 'We will be placing the code in the Dashboard worksheet 6 | '1. Open the VBA IDE 7 | '2. In the project panel, locate and Double-Click on the Dashboard worksheet to open the worksheets VBA window 8 | '3. Move your cursor to the end of any existing code to start entering the following code 9 | '4. Declare the private subroutine, we are going to pass in the selected genre name as a string so declare the parameter as well. This is a subroutine so it will not be returning any values 10 | 11 | Private Sub GenreSales(ByVal pGenre As String) 12 | 13 | '5. Declare the variable we will be using 14 | 15 | Dim RS As Recordset 16 | Dim SQL As String 17 | Dim MyNamedRng As Range 18 | 19 | '6. Start by clearing an existing range data from the location we are going to insert the data. The first time this sub is run, the range does not exists and will cause and error so before attempting to 'clear the range, we ignore errors. After the range is cleared, we start normal error checking. 20 | 21 | On Error Resume Next 22 | Worksheets("Data Sheet").Range("GenreSales").ClearContents 23 | 24 | On Error GoTo HandleError 25 | 26 | '7. Connect to the database, if the connection was successful start processing 27 | 28 | If ConnectDB_DSNless(g_Conn_DSNless) = True Then 29 | 30 | '8. Prepare the SQL statement, we have a view in the database compiling the data so we only need to filter to the genre passed in and select the fields we want to display 31 | 32 | SQL = "" 33 | SQL = SQL & "SELECT SaleMonth, `Units Sold` " 34 | SQL = SQL & "FROM vw_genresales " 35 | SQL = SQL & "WHERE Name = '" & pGenre & "' " 36 | SQL = SQL & "ORDER BY SaleMonth ASC" 37 | 38 | '9. The next code sets the record set variable and opens the record set with the connection 39 | 40 | Set RS = New ADODB.Recordset 41 | RS.Open SQL, g_Conn_DSNless 42 | 43 | 'Test there are records. 44 | If RS.EOF And RS.BOF Then 45 | 'No data 46 | Exit Sub 47 | Else 48 | 49 | '10. We load the data into the “Data Sheet” starting at row 2, column 5 50 | Worksheets("Data Sheet").Cells(2, 5).CopyFromRecordset RS 51 | 52 | '11. We load the data into the “Data Sheet” starting at row 2, column 5 53 | 54 | 'Set and create a named range covering new data 55 | Set MyNamedRng = Worksheets("Data Sheet").Range("E2:F" & RS.RecordCount + 1) 56 | ActiveWorkbook.Names.Add Name:="GenreSales", RefersTo:=MyNamedRng 57 | 58 | '12. The rest of the code finalizes the routine including error handling 59 | 60 | End If 61 | Else 62 | End If 63 | 64 | Leavesub: 65 | 'Close recordset 66 | RS.Close 67 | Set RS = Nothing 68 | Exit Sub 69 | 70 | HandleError: 71 | 72 | MsgBox Err & " " & Error(Err) 73 | Resume Leavesub 74 | End Sub 75 | -------------------------------------------------------------------------------- /Chapter11/Exercise9.13/Exercise – Populate Genre Sales Chart.bas: -------------------------------------------------------------------------------- 1 | 'Note: This code is to go into the Dashboard worksheets Worksheet_Change event 2 | 3 | 'Exercise – Populate Genre Sales Chart 4 | 5 | 6 | '2. To test what cell was changed, we test the Target parameter, this is a Range object and amongst other things, contains the Address and the Value, and we are interested in both. Test the address of 'Target using a Select Case statement to test if the changed cell is B5 7 | 8 | 9 | Private Sub Worksheet_Change(ByVal Target As Range) 10 | 'Test the active cell (the one that changed) 11 | Select Case Target.Address 12 | 13 | Case "$B$5" 14 | 15 | '3. If the target is referring to B5 then we need to process it, start by calling the data load routine we created in the previous exercise. Target will contain the selected Genre text, this is very 'convenient, we only need to pass in Target. 16 | 17 | 'The change was in the dropdown, target has the value 18 | Call GenreSales(Target) 19 | 20 | '4. Activate the Dashboard worksheet so we can use the With/End With construct 21 | 22 | 'Set the chart details Population 23 | Worksheets("Dashboard").ChartObjects("chrtPopulation").Activate 24 | 25 | '5. Set the parameters for the chart including datasource, title and series name 26 | 27 | With ActiveChart 28 | .SetSourceData Source:=Sheets("Data Sheet").Range("GenreSales"), PlotBy:=xlColumns 29 | .HasTitle = True 30 | .ChartTitle.Text = "Genre Sales - " & Target 31 | .SeriesCollection(1).Name = "Sales" 32 | End With 33 | 34 | '6. We are finished with B5. Include the Else to ignore the cell changes we are not interested in. Note: If you want to include other cells, just add its Case test and code (remember that for the upcoming 'activity) 35 | 36 | Case Else 37 | 'Nothing to work with so leave 38 | Exit Sub 39 | End Select 40 | 41 | Leavesub: 42 | Exit Sub 43 | -------------------------------------------------------------------------------- /Chapter11/MySQL Excel Training Template.xlsm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter11/MySQL Excel Training Template.xlsm -------------------------------------------------------------------------------- /Chapter12/Activity01/CoffeeProducts.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-MySQL-Workshop/d533055a33fcabeb137639706c409b5b17d32533/Chapter12/Activity01/CoffeeProducts.xlsx -------------------------------------------------------------------------------- /Chapter12/Exercise12.01/Exercise – Create the Named DSN Connection function.bas: -------------------------------------------------------------------------------- 1 | 'This code is to go into the MySQLDatabase module 2 | 3 | 4 | 'Exercise – Create the Named DSN Connection function 5 | 'In this exercise we will create a function to connect to the database using a Named DSN 6 | 'Using the module MySQLDatabase, start a new function with two parameters, a connection variable and a string to pass in the name of the Named ODBC. The function will return a Boolean value 7 | 8 | Public Function ConnectDB_ODBC(oConn As ADODB.Connection, ODBCName As String) As Boolean 9 | 10 | '1. Setup error handling and declare the variables we will use 11 | 12 | On Error GoTo HandleError 13 | 14 | Dim Msg As String 15 | Dim str As String 16 | 17 | '2. Setup the connection variable. With Named ODBC it is important to tell the connection which cursor to use, we need to use the client cursor otherwise we will not get the data back as we expected 18 | 19 | 'Set the passed in connection variable to a new connection 20 | Set oConn = New ADODB.Connection 21 | oConn.CursorLocation = adUseClient 22 | 23 | '3. Now we prepare the connection string, this is simply, we use the string we passed in representing the name of the Named DSN. An advantage of this method is we can pass in any Named DSN we have 'available so it is very flexible. This method is very simple compared to DSNless 24 | 25 | 'Prepare the connection string 26 | str = "DSN=" & ODBCName & ";" 27 | 28 | '4. Now we open the connection passing in the connection string we just built 29 | 'Open the connection, if there is a problem, it will happen here 30 | 31 | oConn.Open str 32 | 33 | '5. And the rest is the same as the DSNLess connection, returning to a value to indicate success and handling errors 34 | 35 | 'No problem, good, pass back a True to signify connection was successful 36 | ConnectDB_ODBC = True 37 | 38 | LeaveFunction: 39 | 'and leave 40 | Exit Function 41 | 42 | '6. Include error handling 43 | HandleError: 44 | 'There was a problem, tell the user and include the error number and message 45 | Msg = "There was an error - " & Err & " - " & Error(Err) 46 | MsgBox Msg, vbOKOnly + vbCritical, "Problem Connecting to server" 47 | 48 | 'Pass back a False to signify there was an issue to the calling code 49 | ConnectDB_ODBC = False 50 | 51 | 'Leave the function 52 | Resume LeaveFunction 53 | 54 | '7. Close off the function block 55 | End Function 56 | 57 | 'And we are done, we cannot test this until we create a routine to use it, we will do that in the next exercise 58 | -------------------------------------------------------------------------------- /Chapter12/Exercise12.02/Exercise – GenreTrackSalesStats Function.bas: -------------------------------------------------------------------------------- 1 | 'This code is to go into the MySQLDatabase module 2 | 3 | 'Exercise – GenreTrackSalesStats Function 4 | 5 | '1. In the module MySQLDatabase, create a new function as below. The function will return a Boolean value to indicate success or failure. 6 | 7 | Public Function GenreTrackSalesStats() As Boolean 8 | 9 | '2. Declare the variables we will use and also error handling 10 | 11 | Dim SQL As String 'To store the SQL statement 12 | Dim RS As Recordset 'The Recordset variable 13 | Dim Msg As String 'To display messages 14 | Dim Counter As Integer 'A counter 15 | Dim MyNamedRng As Range ' A range variable 16 | 17 | On Error GoTo HandleError 18 | 19 | '3. Prepare the SQL statement. The SQL combines two views to retrieve our data 20 | 21 | SQL = "" 22 | SQL = SQL & "SELECT " 23 | SQL = SQL & "vw_genre_count.Count - vw_genre_count_no_sales.Count AS Sales, " 24 | SQL = SQL & " vw_genre_count_no_sales.Count AS NoSales, " 25 | SQL = SQL & "vw_genre_count.Genre " 26 | SQL = SQL & "FROM " 27 | SQL = SQL & "vw_genre_count " 28 | SQL = SQL & "LEFT JOIN vw_genre_count_no_sales ON vw_genre_count_no_sales.Genre = vw_genre_count.Genre " 29 | SQL = SQL & "Order BY " 30 | SQL = SQL & "vw_genre_count.Genre" 31 | 32 | '4. Now we call the new ODBC connection function. The difference between this and the DSNless connection is here we are using the global ODBC variable and also passing in the name of the DSN we want to 'use. You can use this function with any Named DSN 33 | 34 | If ConnectDB_ODBC(g_Conn_ODBC, "chinook") = True Then 35 | 36 | '5. Set the recordset variable and open the recordset, passing in the SQL and the global ODBC variable 37 | 38 | Set RS = New ADODB.Recordset 39 | RS.Open SQL, g_Conn_ODBC 40 | 41 | '6. Test we have data and deal with a no data situation 42 | 43 | If RS.EOF And RS.BOF Then 44 | RS.Close 45 | Set RS = Nothing 46 | Msg = "There is no data" 47 | MsgBox Msg, vbOKOnly + vbInformation, "No data to display" 48 | Exit Function 49 | 50 | '7. Else if we have, process it, start by setting the column headings. We are placing the data in columns H, I and J 51 | 52 | Else 53 | For Counter = 0 To RS.Fields.Count - 1 54 | Worksheets("Data Sheet").Cells(1, 8 + Counter) = RS.Fields(Counter).Name 55 | Next 56 | Worksheets("Data Sheet").Cells(2, 8).CopyFromRecordset RS 57 | 58 | '8. Create the Named Range for the data. Columns H and I contain the data for the two series in the chart 59 | 60 | Set MyNamedRng = Worksheets("Data Sheet").Range("H2:I" & RS.RecordCount + 1) 61 | ActiveWorkbook.Names.Add Name:="Sales", RefersTo:=MyNamedRng 62 | 63 | Set MyNamedRng = Worksheets("Data Sheet").Range("J2:J" & RS.RecordCount + 1) 64 | ActiveWorkbook.Names.Add Name:="TrackStatGenre", RefersTo:=MyNamedRng 65 | 66 | '9. Close the recordset and connection 67 | 68 | RS.Close 69 | Set RS = Nothing 70 | g_Conn_ODBC.Close 71 | Set g_Conn_ODBC = Nothing 72 | 73 | '10. Now we want to set some options in the chart so we activate the chart 74 | 75 | Worksheets("Dashboard").ChartObjects("TrackStats").Activate 76 | With ActiveChart 77 | .HasTitle = True 78 | .ChartTitle.Text = "Genre Tracks Sales vs. No Sales" 79 | 80 | '11. Set the charts data source and category to the Named Ranges we defined and also set the series names 81 | 82 | .SetSourceData Source:=Worksheets("Data Sheet").Range("Sales"), PlotBy:=xlColumns 83 | .Axes(xlCategory).CategoryNames = Worksheets("Data Sheet").Range("TrackStatGenre") 84 | 85 | .SeriesCollection(1).Name = "Sales" 86 | .SeriesCollection(2).Name = "No Sales" 87 | End With 88 | GenreTrackSalesStats = True 89 | End If 90 | 91 | '12. From here we handle failed connection and exit the function 92 | 93 | Else 94 | 'Connection failed if gets in here, just drop through to leave 95 | End If 96 | 97 | LeaveFunction: 98 | 'Leave the function 99 | Exit Function 100 | 101 | HandleError: 102 | GenreTrackSalesStats = False 103 | Resume LeaveFunction 104 | 105 | End Function 106 | -------------------------------------------------------------------------------- /Chapter12/Exercise12.03/Exercise – Generic Data Reader Part 2.bas: -------------------------------------------------------------------------------- 1 | 'NOTE: This code is to be added after any existing in the Workbook_Open event 2 | 3 | 4 | 5 | '1. Pass in a query to read data from the customer count view and assign the value to N8 6 | 7 | 'Populate Customer Purchase Details 8 | Worksheets("Dashboard").Cells(8, 14) = runSQL_SingleResult("SELECT * FROM vw_customer_count") 9 | 10 | '2. Pass in a query to call a stored procedure and place the returned value in N9 11 | 12 | Worksheets("Dashboard").Cells(9, 14) = runSQL_SingleResult("call spTotalSales()") 13 | 14 | '3. Finally, pass in a query to find the maximum InvoiceDate from the invoice table and place the returned value in N12 15 | 16 | Worksheets("Dashboard").Cells(12, 14) = runSQL_SingleResult("SELECT MAX(InvoiceDate) FROM invoice") 17 | 18 | -------------------------------------------------------------------------------- /Chapter12/Exercise12.03/Exercise – Generic Data Reader.bas: -------------------------------------------------------------------------------- 1 | 'Exercise – Generic Data Reader 2 | 'This code is to go into the MySQLDatabase module 3 | 4 | 'In this exercise, we will create a single function that you can use to query the database and return a single value only. You will pass in an SQL statement to be executed and the result will be returned. 'We will then demonstrate its use by populating cells N8, N9 and N12 in the Dashboard worksheet 5 | 6 | '1. In the MySQLDatabase module, add a new function. The function will have one parameter, SQL, a string and it will return a Variant type value. Because we do not know what type of value is to be 'returned, a variant type will allow any data type 7 | 8 | Public Function runSQL_SingleResult(SQL As String) As Variant 9 | 10 | '2. Declare the variables to use and also setup error handling 11 | 12 | Dim RS As Recordset 'The Recordset variable 13 | Dim Msg As String 'To display messages 14 | 15 | On Error GoTo HandleError 16 | 17 | '3. Make the connection to the database, we will be using the Named DSN connector and passing in the DSN name to use 18 | 19 | If ConnectDB_ODBC(g_Conn_ODBC, "chinook") = True Then 20 | 21 | '4. Prepare and open the recordset variable RS, pass in the SQL statement that was passed into the function using the ODBC connection 22 | 23 | Set RS = New ADODB.Recordset 24 | RS.Open SQL, g_Conn_ODBC 25 | 26 | '5. Test there was a record returned, if not then close the recordset and connection and return a zero before leaving the function 27 | 28 | If RS.EOF And RS.BOF Then 29 | RS.Close 30 | Set RS = Nothing 31 | 32 | Msg = "There is no data" 33 | MsgBox Msg, vbOKOnly + vbInformation, "No data to display" 34 | runSQL_SingleResult = 0 35 | Exit Function 36 | 37 | '6. If there was a record returned, set the position to the first record and read the value and pass it back by assigning it to the function. Because this function accepts an SQL, we have no idea what the 'fields name maybe, as we expect only one single value to be returned, we can simply read the first (and only) fields value by referring to it using its numeric value of zero 38 | 39 | Else 40 | RS.MoveFirst 41 | runSQL_SingleResult = RS.Fields(0) 42 | 43 | '7. We then close the recordset, connection and make our way out of the function, in the error routine we pass back a zero. 44 | 45 | RS.Close 46 | Set RS = Nothing 47 | End If 48 | 49 | g_Conn_ODBC.Close 50 | Set g_Conn_ODBC = Nothing 51 | 52 | Else 53 | End If 54 | 55 | LeaveFunction: 56 | Exit Function 57 | 58 | HandleError: 59 | runSQL_SingleResult = 0 60 | Resume LeaveFunction 61 | End Function 62 | -------------------------------------------------------------------------------- /Chapter13/.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | *.reject 3 | __pycache__ 4 | -------------------------------------------------------------------------------- /Chapter13/Activity01/ch11_Activity_01.sql: -------------------------------------------------------------------------------- 1 | USE test; 2 | 3 | CREATE TABLE airports ( 4 | iata_code CHAR(3) PRIMARY KEY, 5 | location VARCHAR(255) NOT NULL, 6 | country VARCHAR(255) NOT NULL, 7 | passengers INT NOT NULL 8 | ); 9 | 10 | INSERT INTO airports VALUES 11 | ('ATL', 'Atlanta, Georgia', 'United States', 54388000), 12 | ('PEK', 'Chaoyang-Shunyi, Beijing', 'China', 49242000), 13 | ('LAX', 'Los Angeles, California', 'United States', 43049000), 14 | ('HND', 'Ōta, Tokyo', 'Japan', 41435000), 15 | ('DBX', 'Garhoud, Dubai', 'United Arab Emirates', 41278000); 16 | 17 | SELECT * FROM airports; 18 | 19 | SELECT * FROM airports ORDER BY passengers DESC; 20 | 21 | -------------------------------------------------------------------------------- /Chapter13/Activity02/ch11_Activity_02.js: -------------------------------------------------------------------------------- 1 | \use test 2 | 3 | db.createCollection('airports') 4 | 5 | db.airports.add( 6 | {"iata_code": "ATL", "location": "Atlanta, Georgia", 7 | "country": "United States", "passengers": 54388000}, 8 | {"iata_code": "LAX", "location": "Los Angeles, California", 9 | "country": "United States", "passengers": 43049000}, 10 | {"iata_code": "DBX", "location": "Garhoud, Dubai", 11 | "country": "United Arab Emirates", "passengers": 41278000}, 12 | {"iata_code": "PEK", "location": "Chaoyang-Shunyi, Beijing", 13 | "country": "China", "passengers": 49242000}, 14 | {"iata_code": "HND", "location": "Ōta, Tokyo", 15 | "country": "Japan", "passengers": 41435000} 16 | ) 17 | 18 | db.airports.find() 19 | 20 | db.airports.find().sort('passengers DESC') 21 | 22 | -------------------------------------------------------------------------------- /Chapter13/Activity03/building1.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO climate_history VALUES 2 | ('2020-03-12', 18.5, 62.0), 3 | ('2020-03-13', 19.0, 63.5); 4 | -------------------------------------------------------------------------------- /Chapter13/Activity03/building2.CSV: -------------------------------------------------------------------------------- 1 | "2020-03-12","20","82" 2 | "2020-03-13","18","80" 3 | -------------------------------------------------------------------------------- /Chapter13/Activity03/building3.json: -------------------------------------------------------------------------------- 1 | {"report_date": "2020-03-12", "temp": 19.5, "humidity": 72 } 2 | {"report_date": "2020-03-13", "temp": 19.0, "humidity": 72 } 3 | -------------------------------------------------------------------------------- /Chapter13/Activity03/ch11_Activity_03.js: -------------------------------------------------------------------------------- 1 | \use test 2 | \sql 3 | 4 | CREATE TABLE climate_history ( 5 | report_date date NOT NULL PRIMARY KEY, 6 | temperature DECIMAL(3,1), 7 | humidity DECIMAL(3,1) 8 | ); 9 | 10 | \source building1.sql 11 | 12 | RENAME TABLE climate_history TO building1; 13 | 14 | CREATE TABLE building2 LIKE building1; 15 | 16 | LOAD DATA INFILE "building2.CSV" 17 | INTO TABLE building2 18 | FIELDS TERMINATED BY "," ENCLOSED BY '"'; 19 | 20 | \js 21 | db.createCollection('building3') 22 | util.importJson("building3.json") 23 | \rehash 24 | db.building3.find() 25 | 26 | \sql 27 | CREATE TABLE building_report LIKE building1; 28 | ALTER TABLE building_report 29 | ADD COLUMN building VARCHAR(255) FIRST, 30 | DROP PRIMARY KEY, 31 | ADD PRIMARY KEY (building, report_date); 32 | INSERT INTO building_report 33 | SELECT 'building 1', building1.* FROM building1; 34 | 35 | INSERT INTO building_report 36 | SELECT 'building 2', building2.* FROM building2; 37 | 38 | INSERT INTO building_report 39 | SELECT 40 | 'building 3', 41 | doc->>'$.report_date', 42 | doc->>'$.temp', 43 | doc->>'$.humidity' 44 | FROM building3; 45 | 46 | SELECT * FROM building_report ORDER BY report_date, building; 47 | 48 | SELECT 'building 1' AS building, building1.* 49 | FROM building1 50 | UNION ALL 51 | SELECT 'building 2', building2.* 52 | FROM building2 53 | UNION ALL 54 | SELECT 55 | 'building 3', 56 | doc->>'$.report_date' AS report_date, 57 | doc->>'$.temp' AS temperature, 58 | doc->>'$.humidity' AS humidity 59 | FROM building3 ORDER BY report_date, building; 60 | -------------------------------------------------------------------------------- /Chapter13/Activity04/ch11_Activity_04.sql: -------------------------------------------------------------------------------- 1 | USE world; 2 | 3 | CREATE TABLE city_export_california LIKE city; 4 | 5 | ALTER TABLE city_export_california 6 | DROP INDEX CountryCode, 7 | DROP PRIMARY KEY, 8 | MODIFY COLUMN ID int NOT NULL, 9 | ENGINE=CSV; 10 | 11 | INSERT INTO 12 | city_export_california 13 | SELECT 14 | * 15 | FROM 16 | city 17 | WHERE 18 | CountryCode='USA' 19 | AND District='California'; 20 | 21 | -------------------------------------------------------------------------------- /Chapter13/Exercise01/ch11_Excercise_8_01.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE test; 2 | 3 | use test; 4 | 5 | CREATE TABLE animals ( id int primary key, name varchar(255) ); 6 | 7 | DESCRIBE animals; 8 | 9 | INSERT INTO animals VALUES(1, 'dog'); 10 | 11 | SELECT * FROM animals; 12 | 13 | ROLLBACK; 14 | 15 | SELECT * FROM animals; 16 | -------------------------------------------------------------------------------- /Chapter13/Exercise02/ch11_Excercise_8_02.sql: -------------------------------------------------------------------------------- 1 | USE test; 2 | 3 | DESCRIBE animals; 4 | 5 | INSERT INTO animals (name, id) VALUES('Camel', 2); 6 | 7 | INSERT INTO animals (id) VALUES(3); 8 | 9 | SELECT * FROM animals; 10 | -------------------------------------------------------------------------------- /Chapter13/Exercise03/ch11_Excercise_8_03.sql: -------------------------------------------------------------------------------- 1 | USE test; 2 | 3 | DESCRIBE animals; 4 | 5 | TRUNCATE TABLE animals; 6 | 7 | BEGIN; 8 | 9 | INSERT INTO animals VALUES(1, 'dolphin'); 10 | 11 | SELECT * FROM animals; 12 | 13 | ROLLBACK; 14 | 15 | SELECT * FROM animals; 16 | -------------------------------------------------------------------------------- /Chapter13/Exercise04/ch11_Excercise_8_04.sql: -------------------------------------------------------------------------------- 1 | USE test; 2 | 3 | CREATE TABLE months ( 4 | month_number tinyint unsigned primary key, 5 | month_name varchar(15), 6 | CHECK (month_number <= 12) 7 | ); 8 | DESCRIBE months; 9 | INSERT INTO months VALUES (1, 'January'); 10 | 11 | --error 1136 12 | INSERT INTO months VALUES ('February'); 13 | 14 | --error 1366 15 | INSERT INTO months VALUES ('February', 2); 16 | 17 | --error 3819 18 | INSERT INTO months VALUES (15, 'February'); 19 | 20 | --error 1406 21 | INSERT INTO months VALUES (2, 'The month February'); 22 | -------------------------------------------------------------------------------- /Chapter13/Exercise05/ch11_Excercise_8_05.sql: -------------------------------------------------------------------------------- 1 | USE test; 2 | 3 | CREATE TABLE furniture ( 4 | id INT PRIMARY KEY, 5 | description VARCHAR(255), 6 | room VARCHAR(255) 7 | ); 8 | 9 | INSERT INTO furniture VALUES 10 | (1, 'couch', 'living room'), 11 | (2, 'bed', 'bedroom'), 12 | (3, 'small table', 'kitchen'); 13 | 14 | --error 1062 15 | INSERT INTO furniture VALUES 16 | (4, 'bed', 'second bedroom'), 17 | (1, 'table', 'second bedroom'); 18 | 19 | SELECT * FROM furniture; 20 | -------------------------------------------------------------------------------- /Chapter13/Exercise06/ch11_Excercise_8_06.js: -------------------------------------------------------------------------------- 1 | \use test 2 | \sql DESCRIBE animals 3 | db.animals.insert().values(4, 'Cheetah') 4 | db.animals.insert().values(5, 'Leopard') 5 | db.animals.select() 6 | -------------------------------------------------------------------------------- /Chapter13/Exercise07/ch11_Excercise_8_07.js: -------------------------------------------------------------------------------- 1 | \use test 2 | db.createCollection('countries'); 3 | db.countries.add({"code": "FR", "name": "France"}); 4 | db.countries.add({"code": "DE", "name": "Germany"}); 5 | db.countries.add({"code": "IT", "name": "Italy"}); 6 | db.countries.find(); 7 | db.countries.add( 8 | {"code": "BE", "name": "Belgium"}, 9 | {"code": "PL", "name": "Poland"} 10 | ); 11 | db.countries.find('code = "PL"'); 12 | db.countries.createIndex('code', 13 | {"fields": 14 | {"field": "$.code"} 15 | } 16 | ); 17 | -------------------------------------------------------------------------------- /Chapter13/Exercise08/ch11_Excercise_8_08.sql: -------------------------------------------------------------------------------- 1 | # source world.sql 2 | SHOW TABLES FROM world; 3 | DESCRIBE world.city; 4 | -------------------------------------------------------------------------------- /Chapter13/Exercise09/ch11_Exercise_8_09.sql: -------------------------------------------------------------------------------- 1 | DROP DATABASE world; -------------------------------------------------------------------------------- /Chapter13/Exercise10/ch11_Excercise_8_10.sql: -------------------------------------------------------------------------------- 1 | USE world; 2 | 3 | SELECT * FROM city INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/city.csv' CHARACTER SET utf8mb4 4 | FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n'; 5 | --cat_file /var/lib/mysql-files/city.csv 6 | 7 | CREATE TABLE copy_of_city LIKE city; 8 | LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/city.csv' INTO TABLE copy_of_city 9 | FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n'; 10 | 11 | -------------------------------------------------------------------------------- /Chapter13/Exercise11/ch11_Excercise_8_11.js: -------------------------------------------------------------------------------- 1 | util.importJson('the_beatles.json'); 2 | \rehash 3 | db.the_beatles.find(); 4 | -------------------------------------------------------------------------------- /Chapter13/Exercise11/the_beatles.json: -------------------------------------------------------------------------------- 1 | {"name": "Rubber Soul"} 2 | {"name": "Revolver"} 3 | {"name": "Sgt. Pepper's Lonely Hearts Club Band"} 4 | {"name": "Magical Mystery Tour"} 5 | {"name": "Yellow Submarine"} 6 | -------------------------------------------------------------------------------- /Chapter13/Exercise12/ch11_Excercise_8_12.sql: -------------------------------------------------------------------------------- 1 | USE world; 2 | 3 | CREATE TABLE city_export LIKE city; 4 | SHOW CREATE TABLE city_export; 5 | 6 | ALTER TABLE city_export MODIFY COLUMN `ID` int NOT NULL; 7 | ALTER TABLE city_export DROP KEY CountryCode; 8 | ALTER TABLE city_export DROP PRIMARY KEY; 9 | ALTER TABLE city_export ENGINE=CSV; 10 | 11 | INSERT INTO city_export SELECT * FROM city WHERE CountryCode='RUS'; 12 | 13 | SELECT @@datadir; 14 | # \! head /path/to/world/city_export.CSV 15 | -------------------------------------------------------------------------------- /Chapter13/Exercise13/ch11_Excercise_8_13.sql: -------------------------------------------------------------------------------- 1 | USE world; 2 | SELECT * FROM city_export WHERE District='Moskova'; 3 | # Now modify the city_export.CSV file 4 | FLUSH TABLE city_export; 5 | SELECT * FROM city_export WHERE District='Moskova'; 6 | 7 | -------------------------------------------------------------------------------- /Chapter13/XDEV/animals.sql: -------------------------------------------------------------------------------- 1 | USE test; 2 | 3 | DROP TABLE animals; 4 | 5 | CREATE TABLE animals ( 6 | id int(11) NOT NULL, 7 | name varchar(255) DEFAULT NULL, 8 | PRIMARY KEY (id) 9 | ); 10 | 11 | CREATE TABLE animals_collection ( 12 | doc json DEFAULT NULL, 13 | _id varbinary(32) GENERATED ALWAYS AS (json_unquote(json_extract(`doc`,_utf8mb4'$._id'))) STORED NOT NULL, 14 | PRIMARY KEY (`_id`) 15 | ); 16 | INSERT INTO animals VALUES (1,'dog'),(2,'Camel'),(3,NULL); 17 | 18 | INSERT INTO animals_collection (`doc`) VALUES ('{\"_id\": 1, \"name\": \"monkey\"}'),('{\"_id\": 2, \"name\": \"zebra\"}'),('{\"_id\": 3, \"name\": \"lion\"}'); 19 | -------------------------------------------------------------------------------- /Chapter13/XDEV/ch08_02_X_DevApi.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Expects datbase with two tables created from animals.sql 3 | import mysql.connector 4 | import mysqlx 5 | 6 | def sql_example(): 7 | con = mysql.connector.connect( 8 | host='localhost', 9 | user='msandbox', 10 | password='msandbox', 11 | database='test', 12 | ) 13 | c = con.cursor() 14 | c.execute("SELECT name FROM animals") 15 | output = "Animals in the animals table\n" 16 | for row in c: 17 | output += "SQL Animal: {0}\n".format(row[0]) 18 | c.close() 19 | con.close() 20 | return output 21 | 22 | def nosql_example(): 23 | session = mysqlx.get_session( 24 | host='localhost', 25 | user='msandbox', 26 | password='msandbox', 27 | ) 28 | schema = session.get_schema('test') 29 | animals = schema.get_collection('animals_collection') 30 | output = "Animals in the animals collection\n" 31 | for doc in animals.find().fields('name').execute().fetch_all(): 32 | output += "NoSQL Animal: {0}\n".format(doc['name']) 33 | session.close() 34 | return output 35 | 36 | def test_sql_example(): 37 | assert sql_example() == """Animals in the animals table 38 | SQL Animal: dog 39 | SQL Animal: Camel 40 | SQL Animal: None 41 | """ 42 | 43 | def test_nosql_example(): 44 | assert nosql_example() == """Animals in the animals collection 45 | NoSQL Animal: monkey 46 | NoSQL Animal: zebra 47 | NoSQL Animal: lion 48 | """ 49 | 50 | if __name__ == "__main__": 51 | print(sql_example()) 52 | print(nosql_example()) 53 | print(test_sql_example()) 54 | print(test_nosql_example()) 55 | -------------------------------------------------------------------------------- /Chapter14/Activity16.01/ch16_activity_01.sql: -------------------------------------------------------------------------------- 1 | --disable_warnings 2 | DROP ROLE IF EXISTS 'manager'; 3 | DROP ROLE IF EXISTS 'language_expert'; 4 | DROP USER IF EXISTS 'webserver'@'%'; 5 | DROP USER IF EXISTS 'intranet'@'%'; 6 | DROP USER IF EXISTS 'stewart'@'%'; 7 | DROP USER IF EXISTS 'sue'@'%'; 8 | --enable_warnings 9 | 10 | CREATE ROLE 'manager'; 11 | GRANT ALL ON world.* TO 'manager'; 12 | CREATE ROLE 'language_expert'; 13 | GRANT ALL ON world.countrylanguage TO 'language_expert'; 14 | 15 | CREATE USER 'webserver'@'%' IDENTIFIED BY '1twedByutGiawWy'; 16 | GRANT SELECT ON world.* TO 'webserver'@'%'; 17 | 18 | CREATE USER 'intranet'@'%' IDENTIFIED BY 'JiarjOodVavit'; 19 | GRANT INSERT, UPDATE, SELECT ON world.* TO 'intranet'@'%'; 20 | 21 | CREATE USER 'stewart'@'%' 22 | IDENTIFIED BY 'UkfejmuniadBekMow4' 23 | DEFAULT ROLE manager; 24 | 25 | CREATE USER 'sue'@'%' 26 | IDENTIFIED BY 'WrawdOpAncy' 27 | DEFAULT ROLE language_expert; 28 | -------------------------------------------------------------------------------- /Chapter14/Exercise16.01/ch16_excercise_16_01.sql: -------------------------------------------------------------------------------- 1 | --disable_warnings 2 | CREATE SCHEMA IF NOT EXISTS employees; 3 | CREATE SCHEMA IF NOT EXISTS ebike; 4 | DROP USER IF EXISTS 'patrick'@'%'; 5 | DROP USER IF EXISTS 'mike'@'%'; 6 | DROP USER IF EXISTS 'webserver'@'%'; 7 | --enable_warnings 8 | 9 | CREATE USER 'patrick'@'%' IDENTIFIED BY 'NijTaseirpyocyea'; 10 | CREATE USER 'mike'@'%' IDENTIFIED BY 'MyhafDixByej'; 11 | CREATE USER 'webserver'@'%' IDENTIFIED BY 'augJigFevni' WITH MAX_USER_CONNECTIONS 300; 12 | GRANT ALL ON employees.* TO 'patrick'@'%'; 13 | GRANT ALL ON ebike.* TO 'patrick'@'%'; 14 | GRANT ALL ON ebike.* TO 'mike'@'%'; 15 | GRANT SELECT, INSERT, UPDATE, DELETE ON ebike.* TO 'webserver'@'%'; 16 | -------------------------------------------------------------------------------- /Chapter14/Exercise16.02/ch16_excercise_16_02.sql: -------------------------------------------------------------------------------- 1 | --disable_warnings 2 | DROP USER IF EXISTS 'sarah'@'%'; 3 | DROP USER IF EXISTS 'webserver2'@'%'; 4 | --enable_warnings 5 | 6 | CREATE USER 'sarah'@'%' IDENTIFIED BY 'IkbyewUgJeuj8'; 7 | GRANT ALL ON ebike.* TO 'sarah'@'%'; 8 | GRANT ALL ON mobileapp.* TO 'sarah'@'%'; 9 | 10 | GRANT ALL ON mobileapp.* TO 'mike'@'%'; 11 | GRANT ALL ON mobileapp.* TO 'patrick'@'%'; 12 | GRANT ALL ON mobileapp.* TO 'webserver'@'%'; 13 | 14 | REVOKE ALL ON ebike.* FROM 'mike'@'%'; 15 | 16 | ALTER USER 'patrick'@'%' IDENTIFIED BY 'WimgeudJa'; 17 | 18 | # SHOW GRANTS FOR 'webserver'@'%'; 19 | 20 | CREATE USER 'webserver2'@'%' IDENTIFIED BY 'dutPyicloHi' WITH MAX_USER_CONNECTIONS 300; 21 | GRANT SELECT, INSERT, UPDATE, DELETE ON ebike.* TO webserver2@'%'; 22 | GRANT ALL PRIVILEGES ON mobileapp.* TO webserver2@'%'; 23 | 24 | ALTER USER 'webserver'@'%' ACCOUNT LOCK; 25 | -------------------------------------------------------------------------------- /Chapter14/Exercise16.03/ch16_excercise_16_03.sql: -------------------------------------------------------------------------------- 1 | --disable_warnings 2 | DROP ROLE IF EXISTS 'manager'; 3 | DROP ROLE IF EXISTS 'webdeveloper'; 4 | DROP ROLE IF EXISTS 'appdeveloper'; 5 | DROP USER IF EXISTS 'linda'@'%'; 6 | DROP USER IF EXISTS 'john'@'%'; 7 | DROP USER IF EXISTS 'vladimir'@'%'; 8 | DROP USER IF EXISTS 'jack'@'%'; 9 | --enable_warnings 10 | 11 | CREATE ROLE 'manager'; 12 | GRANT ALL ON employees.* TO 'manager'; 13 | CREATE ROLE 'webdeveloper'; 14 | GRANT ALL ON ebike.* TO 'webdeveloper'; 15 | CREATE ROLE 'appdeveloper'; 16 | GRANT ALL ON mobileapp.* TO 'appdeveloper'; 17 | 18 | CREATE USER 'linda'@'%' IDENTIFIED BY 'AkFernyeisjegs' DEFAULT ROLE manager; 19 | CREATE USER 'john'@'%' IDENTIFIED BY 'owvurewJatkinyegod' DEFAULT ROLE manager; 20 | CREATE USER 'vladimir'@'%' IDENTIFIED BY 'rusvawfyoaw' DEFAULT ROLE appdeveloper; 21 | CREATE USER 'victoria'@'%' IDENTIFIED BY 'joigowInladdIc6' DEFAULT ROLE webdeveloper; 22 | 23 | GRANT manager, webdeveloper, appdeveloper TO 'patrick'@'%'; 24 | ALTER USER 'patrick'@'%' DEFAULT ROLE manager; 25 | GRANT webdeveloper, appdeveloper TO 'mike'@'%'; 26 | ALTER USER 'mike'@'%' DEFAULT ROLE webdeveloper, appdeveloper; 27 | GRANT webdeveloper, appdeveloper TO 'sarah'@'%'; 28 | ALTER USER 'sarah'@'%' DEFAULT ROLE webdeveloper, appdeveloper; 29 | -------------------------------------------------------------------------------- /Chapter15/.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | *.reject 3 | -------------------------------------------------------------------------------- /Chapter15/Activity17.01/ch17_Activity_01.bat: -------------------------------------------------------------------------------- 1 | :: Backup the schema 2 | mysqldump -u root -p world > "C:\Temp\world_backup.sql" 3 | :: continue with sql file 4 | :: restore schema 5 | mysql -u root -p world < "C:\Temp\world_backup.sql" -------------------------------------------------------------------------------- /Chapter15/Activity17.01/ch17_Activity_01.sql: -------------------------------------------------------------------------------- 1 | USE world; 2 | DELETE FROM city; 3 | SELECT * FROM city; 4 | -- below works after restore 5 | SELECT COUNT(*) FROM city; -------------------------------------------------------------------------------- /Chapter15/Activity17.02/ch17_Activity_02.bat: -------------------------------------------------------------------------------- 1 | mysqldump --master-data=2 -u root -p world > "C:\Temp\backup_world_pitr.sql" 2 | :: this is done later 3 | mysqlbinlog -u root -p -–skip-gtids --stop-position=522 "C:\ProgramData\MySQL\MySQL Server 8.0\Data\PPMUMCPU0032-bin.000001" > "C:\Temp\restore_world_pitr.sql" 4 | mysql -u root -p world < "C:\Temp\backup_world_pitr.sql" 5 | mysql -u root -p < "C:\Temp\restore_world_pitr.sql" -------------------------------------------------------------------------------- /Chapter15/Activity17.02/ch17_Activity_02.sql: -------------------------------------------------------------------------------- 1 | RESET MASTER; 2 | -- This works after bat first is run 3 | USE world; 4 | UPDATE city SET Population=123456789 WHERE name = 'Toulouse'; 5 | DELETE FROM city; 6 | SHOW MASTER LOGS; 7 | SHOW BINLOG EVENTS IN 'binlog.000001'; 8 | -- this is ran after restore. -------------------------------------------------------------------------------- /Chapter15/Exercise17.01/ch17_Excercise_17_01.sql: -------------------------------------------------------------------------------- 1 | CREATE SCHEMA coffeeprefs; 2 | USE coffeeprefs; 3 | 4 | CREATE TABLE coffeeprefs ( 5 | name VARCHAR(255), 6 | preference VARCHAR(255), 7 | PRIMARY KEY(name) 8 | ); 9 | 10 | INSERT INTO coffeeprefs VALUES 11 | ("John", "Capuchino"), 12 | ("Sue", "Cortado"), 13 | ("Peter", "Flat White"); 14 | -------------------------------------------------------------------------------- /Chapter15/Exercise17.01/ch17_Exercise_17_01_dump.bat: -------------------------------------------------------------------------------- 1 | mysqldump -u root -p --single-transaction --no-data coffeeprefs > "C:\Temp\coffeeprefs.sql" -------------------------------------------------------------------------------- /Chapter15/Exercise17.01/ch17_Exercise_17_01_fulldump.bat: -------------------------------------------------------------------------------- 1 | mysqldump -u root -p --single-transaction coffeeprefs > "C:\Temp\coffeeprefs_backup.sql" -------------------------------------------------------------------------------- /Chapter15/Exercise17.02/ch17_Exercise_17_02_backup_pump.bat: -------------------------------------------------------------------------------- 1 | mysqlpump -u root -p --single-transaction --set-gtid-purged=OFF --compress-output zlib coffeeprefs --result-file="C:\Temp\coffeeprefs.sql.gz" 2 | 3 | zlib_decompress 4 | "C:\Temp\coffeeprefs.sql.gz" 5 | "C:\Users\BHAVESH\Desktop\Coffee\coffeeprefs.sql" -------------------------------------------------------------------------------- /Chapter15/Exercise17.03/ch17_Exercise_17_03_restore_backup.bat: -------------------------------------------------------------------------------- 1 | mysqldump -u root -p --single-transaction coffeeprefs > "C:\Temp\coffeeprefs.sql" -------------------------------------------------------------------------------- /Chapter15/Exercise17.03/ch17_Exercise_17_03_restore_backup.sql: -------------------------------------------------------------------------------- 1 | CREATE SCHEMA coffeeprefs_dev; 2 | USE coffeeprefs_dev; 3 | SOURCE C:\Temp\coffeeprefs.sql 4 | SHOW TABLES; 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Packt Workshops 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The-MySQL-Workshop 2 | A simple, low tech approach to quickly get you working with MySQL with real world examples from those who use it every day. 3 | --------------------------------------------------------------------------------