IT Session 3 & 4 - MySQL Basics

9m ago
8 Views
1 Downloads
718.92 KB
14 Pages
Last View : 20d ago
Last Download : 3m ago
Upload by : Kaleb Stephen
Transcription

Assigned Number: IT Session 3 & 4 – MySQL Basics 1 The MySQL Database . 2 2 Making your database connection . 2 3 Inside MySQL. 3 3.1 4 A MySQL Table. 3 MySQL Basics. 3 4.1.1 Creating Tables . 4 4.1.2 Inserting Data into Tables . 5 4.1.3 Deleting Table Content. 7 4.1.4 Selecting Data from a Table And Updating. 8 4.1.4.1 Selecting All Data and Updating Records . 8 4.1.4.2 Selecting Particular Rows . 8 4.1.4.3 Selecting Particular Columns . 10 4.1.4.4 Ordered Selection . 11 4.1.5 5 Date Calculation. 12 Is That All?. 14

Introduction to Web Applications – IT Session 4 and 5 2 1 The MySQL Database MySQL is a relational database management system. A relational database is a special kind of database that organizes data into tables and represents relationships among those tables. MySQL has many features that makes is widely used. The first feature is that it a multithreading server, which means that it suits for performance design goals. Besides that, MySQL supports openness in every sense of the term. It runs on countless platforms, including Windows, Mac OS, Linux, FreeBSD and Solaris. If no binary code is available for another platform, you have access to the source to compile to that platform. Some of the other features, we are going to explore in the following two weeks. The content of this worksheet will be also used for the next week, so remember to bring it back with you next week. 2 Making your database connection The database we are going to use is installed in a remote server. In this course we going to use a graphical interface for MySQL database server, supported by PhPmyAdmin available at the UCL web site. So open the web browser and go to http://www.ucl.ac.uk/is/mysql/admin/ Fill in the login fields as follows: Username: uczlw3e user Password: student DB*EFREI Then, click on the button Login. Once you logged in successfully, you will see a welcome message on the right frame of the page: Welcome to phpMyAdmin 2.6.4-pl2 On the top of the left frame, there are four icons, that can be very useful to know: If you pass the mouse over them, you will find out what they stand for. For the purpose of this course, the button we are going to use more frequently is the Query Window which will be used to write our SQL queries. Click on each button to find out their purpose, but beware that if you press the Logout button you will have to login again. You don’t have to worry about the phpMyAdmin Documentation button Documentation button , but the MySQL can be quite useful for you to know detailed information about the SQL commands we are going to run and much more. All free for you! Check it out. Below those buttons, on the left frame of your session page, there are the list of the tables stored on the database uczlw3e, where you will show the tables you will create and manipulate throughout this course.

Introduction to Web Applications – IT Session 4 and 5 3 3 Inside MySQL Inside the MySQL server, you can create databases where you want the MySQL server to store your set of tables. Inside the database we are going to put all the tables containing information we want to store. 3.1 A MySQL Table A table in MySQL has 6 structures: Field, Type, Null, Key, Default and Extra. There is a table in the database uczlw3e called USER, as you can see listed on the tables list on the left frame. Press the button Query Window and type the following command to see the structure the table USER: describe USER Press the button Go on the right bottom corner of the Query Window screen. On the right frame of your session page, you will see the structures that compose an SQL table. We are going to talk briefly about each of these structures: Field – The columns of the table. They correspond to the fields which will hold the actual values stored in the table. Type – Corresponds to the SQL type of the table field. Null – A boolean value (Yes/No) if the column value can be null. This is useful when the creator of the table wants to assure that the value of that table column can be NULL or not. By default, table columns are NULL. Key – Indicates what kind of key the table column is. In case of the field USER ID, it is indicated a PRImary key. A primary key uniquely identifies a piece of data and avoid clashes of redundant data in the table. Default – Holds a default value in case no data is entered for a certain table column while inserting values into the table. Extra - any extra information to describe the table column. Hint 1: The MySQL environment is case sensitive for the table name, which means, for example, that table USER is different from table user. The command describe USER would return a different result if you typed USER with lowercase letters (i.e. user). Try it yourself! 4 MySQL Basics There are commands to deal with the MySQL database. For example, how to insert values into or to select values from a table in MySQL? We are going to introduce some of those commands, but for further reference we recommend having a look at the MySQL documentation website in http://dev.mysql.com/doc/refman/5.0/en/ The basic SQL functions we need to know for this course are: CREATING TABLES, INSERTING DATA INTO TABLES, DELETING TABLE CONTENTS, SELECTING ALL AND PARTICULAR DATA FROM TABLES,

Introduction to Web Applications – IT Session 4 and 5 4 UPDATING TABLES. We are going to explain these functions briefly below. 4.1.1 Creating Tables The first step is to decide what the structure of your database should be: what tables you will need and what columns will be in each of them. You’ll want a table that contains a record for each of your pets. This can be called the pet table, and it should contain, as a bare minimum, each animal’s name. Because the name by itself is not very interesting, the table should contain other information. For example, if more than one person in your family keeps pets, you might want to list each animal’s owner. You might also want to record some basic descriptive information such as species and sex. You can probably think of other types of information that would be useful in the pet table, but the ones identified so far are sufficient for now: name, owner, species, sex, birth, and death. Use a CREATE TABLE statement to specify the layout of your table (Note that YOUR ASSIGNED NUMBER has to be filled with your folder number). Before going through the table creation, let’s open an editor to edit the sql commands. To do this, we are going to use the editor that comes with MySQL. Click on the Query Window button and type the following commands, where you should substitute YOUR ASSIGNED NUMBER for the number on the top right corner on the first page of this document: CREATE TABLE petYOUR ASSIGNED NUMBER (name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), birth DATE, death DATE); Now press the button Go. If successful, you will see on the right frame of the session page the following screen: And the SQL create statement underneath the message will be presented to you with different syntax colours. If you have an error message, press the button Back and you can re-edit the command above. VARCHAR is a good choice of type for the name, owner, and species columns because the column values will vary in length. The lengths of those columns need not all be the same, and need not be 20. You can pick any length from 1 to 255, whatever seems most reasonable to

Introduction to Web Applications – IT Session 4 and 5 5 you. (If you make a poor choice and it turns out later that you need a longer field, MySQL provides an ALTER TABLE statement.) Several types of values can be chosen to represent sex in animal records, such as 'm' and 'f', or perhaps 'male' and 'female'. It’s simplest to use the single characters 'm' and 'f'. The use of the DATE data type for the birth and death columns is a fairly obvious choice. To verify that your table was created the way you expected, look for it among the list of tables and click on it. Your table should look like the following screenshot: If we want to create a more complex table with keys, we need to put other commands in our CREATE TABLE statement. Have a look at the script below: CREATE TABLE USER ( USER ID INT NOT NULL PRIMARY KEY AUTO INCREMENT, USER NAME CHAR(10) NOT NULL, LAST NAME VARCHAR(30), FIRST NAME VARCHAR(30), OFFICE CHAR(2) NOT NULL DEFAULT 'NY'); We need to observe some features in the SQL command above: The USER ID field is required to be NOT NULL. This means that whatever data someone inserts into the table USER, the field USER ID must be assigned a value. The USER ID is of type INT. As a key field, it’s frequently useful to make them as integer type so you can have a wide range of values to attribute to it. The USER ID is also described as a PRIMARY KEY field. This means that this field has unique value. By calling a column a primary key at creation, you are naming it as unique index that guarantees no clashes of data when you want to query a specific data or when you want to make table joins (For table join, refer to sub-section Error! Reference source not found.). You can use MySQL to help you to insert unique values into your table using the AUTO INCREMENT function, as described above. The OFFICE field has a DEFAULT value. If a row is inserted into the table without a value for this field, this value will be inserted. If a default is not defined, a null value is inserted, unless the field is defined as NOT NULL (like field USER NAME), in which case MySQL picks a value based on the type of the field. 4.1.2 Inserting Data into Tables After creating your table, you need to insert data into it, which is usually referred as populating a table. The INSERT statement is useful for this. Suppose that your pet records can be described as shown here. (Observe that MySQL expects dates in 'YYYY-MM-DD' format). You could add a new record using an INSERT statement like this: INSERT INTO petYOUR ASSIGNED NUMBER VALUES L);

Introduction to Web Applications – IT Session 4 and 5 6 Hint 2: string and date values are specified as quoted strings here, like 'Puffball'and '1999-03-30'. Also, with INSERT, you can insert NULL directly to represent a missing value, when the table column allows null values. We can also make multiple insertions into the table at once. For example: INSERT INTO petYOUR ASSIGNED NUMBER VALUES L); INSERT INTO petYOUR ASSIGNED NUMBER VALUES ('Garfield','Jon','cat','m','2001-04-15',NULL); INSERT INTO petYOUR ASSIGNED NUMBER VALUES ('Pluto','Mickey','dog','m','1997-02-01',NULL); INSERT INTO petYOUR ASSIGNED NUMBER VALUES ('Fifi','Minnie','dog','f','1997-02-01',NULL); To make the insertion of records into your table, follow the instruction below: 1. Create a directory in your R: drive called MySQL Scripts. 2. Open the Notepad editor from Windows Start menu. 3. Use this editor to type the INSERT commands above. Remember to change petYOUR ASSIGNED NUMBER for the actual name of your table. 4. Once you typed the commands, save the file into your directory R:\MySQL Scripts with the name Insert.SQL. 5. To execute the file you created, click on your table on the left-side frame to select the table you want to insert the records. 6. On the bottom of the right side of the screen, choose the file with the INSERT instructions. The place you should look for on the screen looks like the figure below: 7. On that window, choose None for Compression type, as the picture above shows. 8. Click on the button Go. Then you will should see the following screen:

Introduction to Web Applications – IT Session 4 and 5 7 Alternatively, you can click on the Query Window button and type those several insert commands into the editor. After typing all the INSERT statements above, press the button Go in your Query Window. Have a look at the output query, with highlighted colours. Verify that there is a message for each INSERT statement showing that 1 row was affected. There is another and easier way to populate your table. If you click on your table and click on the link Insert, on the frame on the right side of your session page, you can populate your table simply by filling in the text boxes under the Value column. Remember that you need to verify which fields are NULL or NOT NULL, which can be done by simply ticking the field under the column Null. 4.1.3 Deleting Table Content Deleting the rows of a table is very simple. In case you want to delete all the rows, just type the following: DELETE FROM petYOUR ASSIGNED NUMBER; Now, all the data in your table is deleted! But if you followed steps 1 to 8 on previous section, you execute the file Insert.sql following steps 5 to 8 from the previous section. Alternatively, you can populate your table again, by copying the content of the table pet, which was populated with the same values you inserted into your table. In order to do this, you just need to type the following command in your Query Window (but remember to replace petYOUR ASSIGNED NUMBER by your own table name): INSERT INTO petYOUR ASSIGNED NUMBER (select * from pet) Let’s now make a delete command with a particular criterion. For example, suppose you want to delete all "hamster" records: delete from petYOUR ASSIGNED NUMBER where species 'hamster';

Introduction to Web Applications – IT Session 4 and 5 8 4.1.4 Selecting Data from a Table And Updating The SELECT statement is used to pull information from a table. The general form of the statement is: SELECT what to select FROM which table WHERE conditions to satisfy; * what to select indicates what you want to see. This can be a list of columns, or to indicate “all columns”. which table indicates the table from which you want to retrieve data. The WHERE clause is optional. If it’s present, conditions to satisfy specifies conditions that rows must satisfy to qualify for retrieval. Check it out in the MySQL documentation. Hint 2: use backslash ‘\’ to delimit special characters, for example: select * from table where field “c:\\Dir\\subDir\\File.ext” or insert into table value (‘Someone\’s belonging’), where the ‘s is the special character you want to insert into the table. 4.1.4.1 Selecting All Data and Updating Records Let’s then use the command SELECT to query all the data stored in your table: SELECT * FROM petYOUR ASSIGNED NUMBER; This form of SELECT is useful if you want to review your entire table, for example, after you’ve just loaded it with your initial dataset. For example, you may happen to think that the birth date for Puffball doesn’t seem quite right. Consulting your original pedigree papers, you find that the correct birth year should be 1989, not 1999. One way to do is to fix only the erroneous record with an UPDATE statement: UPDATE petYOUR ASSIGNED NUMBER SET birth '1989-03-30' WHERE name 'Puffball'; The UPDATE changes only the record in question and does not require you to reload the table. (Suggestion: Try to make multiple UPDATES, similarly to the INSERT step on page 6). 4.1.4.2 Selecting Particular Rows As shown in the preceding section, it is easy to retrieve an entire table. Just omit the WHERE clause from the SELECT statement. But typically you don’t want to see the entire table. Normally you have a particular question, in which case you specify some constraints on the information you want. Let’s look at some possible selection queries about your pets.

Introduction to Web Applications – IT Session 4 and 5 9 You can select only particular rows from your table. For example, if you want to verify the change that you made to Puffball’s birth date, select Puffball’s record like this: SELECT * FROM pet WHERE name 'Puffball'; And you will have the following result: The result confirms that the year is correctly recorded now as 1989, not 1999. String comparisons normally are case-insensitive, so you can specify the name as 'puffball', 'PUFFBALL', etc. The query result will be the same. You can specify conditions on any column, not just the name. For example, if you want to know which animals were born after 1998, test the birth column: SELECT * FROM pet where birth '1999-01-01'; You can combine conditions, for example, to locate female dogs: SELECT * FROM pet WHERE species 'dog' AND sex 'f'; The preceding query uses the AND logical operator. There is also an OR operator: SELECT * FROM pet WHERE species 'cat' OR species 'dog'; AND and OR may be intermixed, although AND has higher precedence than OR. If you use both operators, it’s a good idea to use parentheses to indicate explicitly how conditions should be grouped: SELECT * FROM pet WHERE (species 'cat' AND sex 'm');

Introduction to Web Applications – IT Session 4 and 5 10 4.1.4.3 Selecting Particular Columns If you don’t want to see entire rows from your table, just name the columns in which you’re interested, separated by commas. For example, if you want to know when your animals were born, select the name and birth columns: SELECT name, birth FROM pet; To find out who owns pets, make the following query: SELECT owner FROM pet; However, notice that the query simply retrieves the owner field from each record, and some of them appear more than once. To minimize the output, retrieve each unique output record just once by adding the keyword DISTINCT: SELECT DISTINCT owner FROM pet; You can use a WHERE clause to combine row selection with column selection. For example, to get birth dates for dogs and cats only, use this query: SELECT name, species, birth FROM petYOUR ASSIGNED NUMBER WHERE species 'dog' OR species 'cat';

Introduction to Web Applications – IT Session 4 and 5 11 4.1.4.4 Ordered Selection You may have noticed in the preceding examples that the result rows are displayed in no particular order. It’s often easier to examine query output when the rows are sorted in some meaningful way. To sort a result, use an ORDER BY clause. Here are animal birthdays, sorted by date: SELECT name, birth FROM pet ORDER BY birth; On character type columns, sorting—like all other comparison operations—is normally performed in a case-insensitive fashion. This means that the order will be undefined for columns using the BINARY cast: ORDER BY BINARY col name. The default sort order is ascending, with smallest values first. To sort in reverse (descending) order, add the DESC keyword to the name of the column you are sorting by: SELECT name, birth FROM pet ORDER BY birth DESC; You can sort on multiple columns, and you can sort columns in different directions. For example, to sort by type of animal in ascending order, then by birth date within animal type in descending order (youngest animals first), use the following query: SELECT name, species, birth FROM pet ORDER BY species, birth DESC; Note that the DESC keyword applies only to the column name immediately preceding it (birth); it does not affect the species column sort order.

Introduction to Web Applications – IT Session 4 and 5 12 4.1.5 Date Calculation MySQL provides several functions that you can use to perform calculations on dates, for example, to calculate ages or extract parts of dates. To determine how old each of your pets is, compute the difference in the year part of the current date and the birth date, then subtract one if the current date occurs earlier in the calendar year than the birth date. The following query shows, for each pet, the birth date, the current date, and the age in years. SELECT name, birth, CURDATE(), (YEAR(CURDATE())-YEAR(birth))(RIGHT(CURDATE(),5) RIGHT(birth,5)) AS age FROM pet; Here, YEAR() pulls out the year part of a date and RIGHT() pulls off the rightmost five characters that represent the MM-DD (calendar year) part of the date. The part of the expression that compares the MM-DD values evaluates to 1 or 0, which adjusts the year difference down a year if CURDATE() occurs earlier in the year than birth. The full expression is somewhat ungainly, so an alias (age) is used to make the output column label more meaningful. The query works, but the result could be scanned more easily if the rows were presented in some order. This can be done by adding an ORDER BY name clause to sort the output by name: SELECT name, birth, CURDATE(), (YEAR(CURDATE())-YEAR(birth)) AS age FROM pet ORDER BY name; (RIGHT(CURDATE(),5) RIGHT(birth,5)) To sort the output by age rather than name, just use a different ORDER BY clause: SELECT name, birth, CURDATE(), (YEAR(CURDATE())-YEAR(birth)) - (RIGHT(CURDATE(),5) RIGHT(birth,5)) AS age FROM pet ORDER BY age;

Introduction to Web Applications – IT Session 4 and 5 13 A similar query can be used to determine age at death for animals that have died. You determine which animals these are by checking whether the death value is NULL. Then, for those with non-NULL values, compute the difference between the death and birth values: SELECT name, birth, death, (YEAR(death)-YEAR(birth)) - (RIGHT(CURDATE(),5) RIGHT(birth,5)) AS age FROM pet WHERE death IS NOT NULL ORDER BY age; And as an output message, you will be prompted: The query is supposed to be empty indeed. However, it shouldn’t be the same result if the term NOT was removed. Try it! Note that the query above uses death IS NOT NULL rather than death NULL because NULL is a special value that cannot be compared using the usual comparison operators. What if you want to know which animals have birthdays next month? For this type of calculation, year and day are irrelevant; you simply want to extract the month of the birth. MySQL provides several date-part extraction functions, such as YEAR(), MONTH(), and DAYOFMONTH(). MONTH() is the appropriate function here. To see how it works, run a simple query that displays the value of both birth and MONTH(birth): SELECT name, birth, MONTH(birth) FROM pet;

Introduction to Web Applications – IT Session 4 and 5 14 Finding animals with birthdays in the upcoming month is easy, too. Suppose that the current month is January. Then the month value is 1 and you look for animals born in February (month 2) like this: SELECT name, birth, MONTH(birth) FROM pet WHERE MONTH(birth) 2; There is a small complication if the current month is December. You don’t just add one to the month number (12) and look for animals born in month 13, because there is no such month. Instead, you look for animals born in January (month 1). You can even write the query so that it works no matter what the current month is. That way you don’t have to use a particular month number in the query. DATE ADD() allows you to add a time interval to a given date. If you add a month to the value of CURDATE(), then extract the month part with MONTH(), the result produces the month in which to look for birthdays: SELECT name, birth FROM pet WHERE MONTH(birth) MONTH(DATE ADD(CURDATE(),INTERVAL 6 MONTH)); 5 Is That All? For our course, hopefully that’s what you need to know. But there is whole world out there. MySQL can be used as a proper Database Management System with administration and multi-users support. You can download it on your PC to play around and develop your skills as a database administrator, which is quite a promising career. If you want to know more about this nice and free database server, go to the official website www.mysql.com. Explore some of the features of a database server that is widely used by developers. For the next steps of the course, we are going to use MySQL in a more interesting and practical way where we will play around with both PHP and MySQL. But this is for our next meeting ;-)

3 Inside MySQL Inside the MySQL server, you can create databases where you want the MySQL server to store your set of tables. Inside the database we are going to put all the tables containing information we want to store. 3.1 A MySQL Table A table in MySQL has 6 structures: Field, Type, Null, Key, Default and Extra. There is a table

Related Documents:

PSI AP Physics 1 Name_ Multiple Choice 1. Two&sound&sources&S 1∧&S p;Hz&and250&Hz.&Whenwe& esult&is:& (A) great&&&&&(C)&The&same&&&&&

Argilla Almond&David Arrivederci&ragazzi Malle&L. Artemis&Fowl ColferD. Ascoltail&mio&cuore Pitzorno&B. ASSASSINATION Sgardoli&G. Auschwitzero&il&numero&220545 AveyD. di&mare Salgari&E. Avventurain&Egitto Pederiali&G. Avventure&di&storie AA.&VV. Baby&sitter&blues Murail&Marie]Aude Bambini&di&farina FineAnna

The program, which was designed to push sales of Goodyear Aquatred tires, was targeted at sales associates and managers at 900 company-owned stores and service centers, which were divided into two equal groups of nearly identical performance. For every 12 tires they sold, one group received cash rewards and the other received

College"Physics" Student"Solutions"Manual" Chapter"6" " 50" " 728 rev s 728 rpm 1 min 60 s 2 rad 1 rev 76.2 rad s 1 rev 2 rad , π ω π " 6.2 CENTRIPETAL ACCELERATION 18." Verify&that ntrifuge&is&about 0.50&km/s,∧&Earth&in&its& orbit is&about p;linear&speed&of&a .

theJazz&Band”∧&answer& musical&questions.&Click&on&Band .

6" syl 4" syl 12" swgl @ 45 & 5' o.c. 12" swchl 6" swl r1-1 ma-d1-6a 4" syl 4" syl 2' 2' r3-5r r4-7 r&d 14.7' 13' cw open w11-15 w16-9p ma-d1-7d 12' 2' w4-3 moonwalks abb r&d r&d r&d r&d r&d r&d ret ret r&d r&d r&d r&d r&d 12' 24' r&d ma-d1-7a ma-d1-7b ret r&d r&d r5-1 r3-2 r&d r&r(b.o.) r6-1r r3-2 m4-5 m1-1 (i-195) m1-1 (i-495) m6-2l om1-1 .

s& . o Look at the poem’s first and last lines (first and last lines may give readers important . it is important to read poems four times. Remind them that the first time they read is for enjoyment; rereads allow them to dive deeper into poems .

01 17-19 YEAR OLDS Session 1: Getting to know each other and getting to know yourself Session 2: Social and gender norms Session 3: Responsibility, choices and consent Session 4: Romantic relationships Session 5: Gender and human rights Session 6: Conception and contraception Session 7: Early and unintended pregnancy Session 8: Sexual health, STIs and HIV Session 9: Talking online