+ All Categories
Home > Software > Database Application with MySQL

Database Application with MySQL

Date post: 07-Jul-2015
Category:
Upload: karwan-mustafa-kareem
View: 878 times
Download: 0 times
Share this document with a friend
Description:
In today's high technology environment, organizations are becoming more and more dependent on their information systems. The public is increasingly concerned about the proper use of data and information. Most Organizations like banks, airlines, markets, manufactures and universities widely used computer systems to manage, manipulate and process their information. Many of today's most widely used computer systems are database applications, for example, Amazon, which was built on top of MySQL. Database application is involved like everywhere in our world, it touches all aspects of our lives. A database application is a computer program whose primary purpose is entering and retrieving information from a computerized database. Early examples of database applications were accounting systems and airline reservations systems. The aim of this course is to explore fundamentals of database application related to MySQL, phpMyAdmin, MySQL command lines, apache server and PHP Maker. It details the relational database principles. It shows how to build and develop database application with web interface. Upon completion of this course, computer students will have gained knowledge of database application concepts and the ability to:  Must know the basic concepts related relational database application.  Must know how to manage relational database via using MySQL command line and phpMyAdmin.  Must know how to build database application with web interface by using MySQL and PHPMaker. A combination of lectures and practical sessions will be used in this course in order to achieve the aim of the course. By MSc. Karwan M. Kareem
Popular Tags:
81
1 Database Database application application Chapter 1: Introduction to MySQL Database Chapter 1: Introduction to MySQL Database Faculty of Physical and Faculty of Physical and Basic Basic Education Education Computer Science Computer Science By: Msc. Karwan M. By: Msc. Karwan M. Kareem Kareem 2014 2014 - - 2015 2015 © University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015
Transcript
Page 1: Database Application with MySQL

1

DatabaseDatabase applicationapplicationChapter 1: Introduction to MySQL DatabaseChapter 1: Introduction to MySQL Database

Faculty of Physical and Faculty of Physical and BasicBasic EducationEducation

Computer ScienceComputer Science By: Msc. Karwan M. By: Msc. Karwan M.

KareemKareem20142014 - - 20152015

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 2: Database Application with MySQL

2

Road MapRoad Map

Introducing Relational Databases Terminology MySQL Database MySQL Command Line Client Managing Databases Manipulating data Summary Examples

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 3: Database Application with MySQL

Introducing Relational Database Introducing Relational Database Database is involved like everywhere in our world

• If we go to bank to deposit or withdraw. • Make hotel and airline reservation.• Purchase something on line.• Buy groceries in supermarkets.

More recent online applications• Youtube • iTunes• Geographic Information Systems (GIS)• Data Warehouses• Many other applications

IRS: assume it has 100 million taxpayers and each taxpayer file 5 forms with 400 characters of information per form=800 Gbyte.

Amazon.com: 15 million people visit per day; about 1000 people are responsible for database update.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015 3

Page 4: Database Application with MySQL

Introducing Relational Database Introducing Relational Database DBMS contains information about a particular enterprise

o Collection of interrelated datao Set of programs to access the data o An environment that is both convenient and efficient to use

Database Applications:o Banking: all transactionso Airlines: reservations, scheduleso Universities: registration, gradeso Sales: customers, products, purchaseso Online retailers: order tracking, customized recommendationso Manufacturing: production, inventory, orders, supply chaino Human resources: employee records, salaries, tax deductions

Databases touch all aspects of our lives

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015 4

Page 5: Database Application with MySQL

Introducing Relational Database Introducing Relational Database A relational database manages data in tables. Databases are managed by a relational database management system

(RDBMS).

An RDBMS supports a database language to create and delete databases and to manage and search data.

The database language used in almost all DBMSs is SQL.

After creating a database, the most common SQL statements used are INSERT to add data UPDATE to change data

DELETE to remove data

SELECT to search data

A database table may have multiple columns, or attributes, each of which has a name.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015 5

Page 6: Database Application with MySQL

6

Introducing Relational Database Introducing Relational Database Tables usually have a primary key, which is one or more values that

uniquely identify each row in a table (Figure 3.1.) Typical DBMS Functionality are

Define a particular database in terms of its data types, structures, and constraints

Construct or Load the initial database contents on a secondary storage medium

Manipulate the database:o Retrieval: Querying, generating reportso Modification: Insertions, deletions and updates to its contento Accessing the database through Web applications

Share a database allows multiple users and programs to access the database simultaneously

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 7: Database Application with MySQL

7

Introducing Relational Database Introducing Relational Database

Figure 3-1. An example of relational database containing two related tables

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 8: Database Application with MySQL

8

Introducing Relational Database Introducing Relational Database A database is modeled using entity-relationship (ER) modeling.

(Figure 3.2.)

Figure 3-2. An example of relational model of the winery database

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 9: Database Application with MySQL

9

TerminologyTerminology Database

A repository to store data. Data

Known facts that can be recorded and have an implicit meaning.

Table

The part of a database that stores the data. A table has columns or attributes, and the data stored in rows.

Attributes

The columns in a table. All rows in table entities have the same attributes. For example, a customer table might have the attributes name, address, and city. Each attribute has a data type such as string, integer, or date.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 10: Database Application with MySQL

10

TerminologyTerminology Rows

The data entries in a table. Rows contain values for each attribute. For example, a row in a customer table might contain the values "Matthew Richardson," "Punt Road," and "Richmond." Rows are also known as records.

Relational model

A model that uses tables to store data and manage the relationship between tables.

Relational database management system A software system that manages data in a database and is based on

the relational model.

Entity-relationship modeling

A technique used to describe the real-world data in terms of entities, attributes, and relationships.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 11: Database Application with MySQL

11

TerminologyTerminology Constraints

Restrictions or limitations on tables and attributes. For example, a wine can be produced only by one winery, an order for wine can't exist if it isn't associated with a customer, having a name attribute could be mandatory for a customer.

Primary key

One or more attributes that contain values that uniquely identify each row. For example, a customer table might have the primary key of cust ID. The cust ID attribute is then assigned a unique value for each customer. A primary key is a constraint of most tables.

Index

A data structure used for fast access to rows in a table. An index is usually built for the primary key of each table and can then be used to quickly find a particular row. Indexes are also defined and built for other attributes when those attributes are frequently used in queries.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 12: Database Application with MySQL

12

TerminologyTerminology Normalized database

A correctly designed database that is created from an ER model. There are different types or levels of normalization, and a third-normal form database is generally regarded as being an acceptably designed relational database.

Foreign key

A foreign key is the linking pin between two tables. SQL

A query language that interacts with a DBMS. SQL is a set of statements to manage databases, tables, and data.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Database system: Database Management System + Database

Page 13: Database Application with MySQL

13

MySQL Database MySQL Database

MySQL DatabaseMySQL is an open source relational database management system (RDBMS)

based on Structured Query Language (SQL).

MySQL is originally developed, distributed, and supported by the Swedish company ( MySQL AB) , was acquired by Oracle in 2008. Developers can still use MySQL under the GNU General Public License (GPL).

Applications which use MySQL databases include: TYPO3, MODx, Joomla, WordPress, phpBB, MyBB, Drupal.

MySQL is also used in many high-profile, large-scale websites, including Google, Facebook, Twitter, Flickr, and YouTube.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 14: Database Application with MySQL

14

MySQL Database MySQL Database

Why are we using MySQL?

MySQL is released under an open-source license. So you have nothing to pay to use it.

MySQL is a very powerful program in its own right. It handles a large subset of the functionality of the most expensive and powerful database packages.

MySQL uses a standard form of the well-known SQL data language. MySQL works on many operating systems ( Windows, UNIX and Linux)

and with many languages including PHP, PERL, C, C++, JAVA etc.

MySQL works very quickly and works well even with large data sets.

MySQL is customizable. The open source GPL license allows programmers to modify the MySQL software to fit their own specific environments.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 15: Database Application with MySQL

15

MySQL Database MySQL Database

Why are we using MySQL?

MySQL is very friendly to PHP and JSP which are most appreciated languages for web development.

MySQL supports large databases, up to 50 million rows or more in a table. The default file size limit for a table is 4GB, but you can increase this to a theoretical limit of 8 million terabytes (TB).

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 16: Database Application with MySQL

16

MySQL Database MySQL Database

Why are we using MySQL?

The following diagrams show the enterprise database market share covered by Gartner and Cloud Database market.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 17: Database Application with MySQL

17

MySQL Database MySQL Database

Interfaces ( Relative MySQL Tools)

Free graphical administration applications (or "front ends") are available that integrate with MySQL and enable users to work with database structure and data visually.LAMP

It’s a Web development platform that uses Linux as the operating system, Apache as the Web server, MySQL as the relational database management system and PHP as the object-oriented scripting language. (Sometimes Perl or Python is used instead of PHP.)

MySQL Command Line Client MySQL Command Line Client is a single exe that allows connecting

and running a sample query. it is a simple SQL shell for creating tables, inserting data, ..etc (with GNU readline capabilities).

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 18: Database Application with MySQL

18

MySQL Database MySQL Database

phpMyAdmin

It's a PHP-driven tool and handles every aspect of creating and managing a MySQL database application. phpMyAdmin also allows for the execution of MySQL commands from within the interface.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 19: Database Application with MySQL

19

MySQL Database MySQL Database

MySQL Workbench

It is a unified visual tool for database architects, developers. MySQL Workbench provides data modeling, SQL development, and administration tools for server configuration, user administration, backup etc.. MySQL Workbench is available on Windows, Linux and Mac OS X.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 20: Database Application with MySQL

20

MySQL Database MySQL Database

HeidiSQL

HeidiSQL – a full featured free front end that runs on Windows, and can connect to local or remote MySQL servers to manage databases, tables, column structure, and individual data records. Also supports specialized GUI features for date/time fields and enumerated multiple-value fields

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 21: Database Application with MySQL

21

MySQL Database MySQL Database

PHPMaker

PHPMaker is a powerful automation tool that can generate a full set of PHP quickly from MySQL, PostgreSQL, Microsoft Access, Microsoft SQL Server and Oracle databases.

Using PHPMaker, you can instantly create web sites that allow users to view, edit, search, add and delete records on the web.

PHPMaker is designed for high flexibility, numerous options enable you to generate PHP database applications that best suits your needs.

The generated codes are clean, straightforward and easy-to-customize.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 22: Database Application with MySQL

22

MySQL Database MySQL Database

PHP Report Maker

PHP Report Maker is a powerful reporting tool that can generate dynamic PHP Web reports from MySQL, PostgreSQL, Microsoft Access, Microsoft SQL Server and Oracle database.

You can instantly create live detail and summary reports or crosstabs reports for your Database Application.

PHP Report Maker is designed for high flexibility, numerous options enable you to generate the reports that best suits your needs.

PHP Report Maker can save you tons of time and is suitable for both beginners and experienced developers alike.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 23: Database Application with MySQL

23

MySQL Database MySQL Database

Apache web server

Apache is a web server package that works under Linux as well as under other operating systems (window, Unix, Etc...)

Apache 1.0 was released on 12/1/1995.

Apache web server developed by the Apache group.

The primary advantage of Apache is that it is generally free or available at modest costs.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 24: Database Application with MySQL

24

MySQL Database MySQL Database

MySQL data type MySQL uses many different data types, broken into three categories:

numeric, date and time, and string types. Numeric Data Types

The MySQL numeric data types are:

INT - A normal-sized integer that the allowable range is from -2147483648 to 2147483647. You can specify a width of up to 11 digits.

TINYINT - A very small integer, the allowable range is from -128 to 127. You can specify a width of up to 4 digits.

SMALLINT - A small integer, the allowable range is from -32768 to 32767. You can specify a width of up to 5 digits.

MEDIUMINT - A medium-sized integer, the allowable range is from -8388608 to 8388607. You can specify a width of up to 9 digits.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 25: Database Application with MySQL

25

MySQL Database MySQL Database

Numeric Data Types

BIGINT - A large integer, the allowable range is from -9223372036854775808 to 9223372036854775807. You can specify a width of up to 11 digits.

FLOAT(M,D) - A floating-point number. You can define the display length (M) and the number of decimals (D). Decimal precision can go to 24 places for a FLOAT.

DOUBLE(M,D) - A double precision floating-point number. You can define the display length (M) and the number of decimals (D). Decimal precision can go to 53 places for a DOUBLE.

DECIMAL(M,D) - An unpacked floating-point number. In unpacked decimals, each decimal corresponds to one byte. Defining the display length (M) and the number of decimals (D) is required.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Note: MySQL uses all the standard ANSI SQL numeric data types ..

Page 26: Database Application with MySQL

26

MySQL Database MySQL Database

Date and Time TypesThe MySQL date and time data types are:

DATE - A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example, December 30th, 1973 would be stored as 1973-12-30.

DATETIME - A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be stored as 1973-12-30 15:30:00.

TIMESTAMP- This looks like the previous DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on December 30th, 1973 would be stored as 19731230153000 ( YYYYMMDDHHMMSS ).

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 27: Database Application with MySQL

27

MySQL Database MySQL Database

Date and Time Types

TIME - Stores the time in HH:MM:SS format.

YEAR(M) - Stores a year in 2-digit or 4-digit format. If the length is specified as 2 (for example YEAR(2)), YEAR can be 1970 to 2069 (70 to 69). If the length is specified as 4, YEAR can be 1901 to 2155. The default length is 4.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 28: Database Application with MySQL

28

MySQL Database MySQL Database

String Types The MySQL String types are:

CHAR(M) - A fixed-length string between 1 and 255 characters in length (for example CHAR(5)). Defining a length is not required, but the default is 1.

VARCHAR(M) - A variable-length string between 1 and 255 characters in length; for example VARCHAR(25). You must define a length when creating a VARCHAR field.

BLOB or TEXT - A field with a maximum length of 65535 characters. BLOBs are "Binary Large Objects" and are used to store large amounts of binary data, such as images or other types of files. Defining a length is not required.

TINYBLOB or TINYTEXT - A BLOB or TEXT column with a maximum length of 255 characters.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 29: Database Application with MySQL

29

MySQL Database MySQL Database

String Types

MEDIUMBLOB or MEDIUMTEXT - A BLOB or TEXT column with a maximum length of 16777215 characters.

LONGBLOB or LONGTEXT - A BLOB or TEXT column with a maximum length of 4294967295 characters.

ENUM - An enumeration, which is a fancy term for list. When defining an ENUM, you are creating a list of items from which the value must be selected (or it can be NULL). For example, if you wanted your field to contain "A" or "B" or "C", you would define your ENUM as ENUM ('A', 'B', 'C').

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 30: Database Application with MySQL

30

MySQL Command Line Client MySQL Command Line Client

Connecting to MySQL MySQL provides an interactive shell for creating tables, inserting data,

etc… On Windows, just go to C:\AppServ\MySQL\bin\MySQL.exe Or, go to start menu all rograms Appserve click on the

Windows icon

Connecting to MySQL Command Line Client ..

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 31: Database Application with MySQL

31

MySQL Command Line Client MySQL Command Line Client

Sample Session

Enter password: *****Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 241 to server version: 5.0.51b-community-nt-log MySQL

Community Edition < GPL>

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

To exit the MySQL Command , just type QUIT or EXIT:

mysql> QUITmysql> exit

MySQL Command Line Client …

Note: MySQL Command Line Client is a single exe that allows connecting and running a sample query. it is a simple SQL shell (with GNU readline capabilities).

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 32: Database Application with MySQL

32

MySQL Command Line Client MySQL Command Line Client

Basic Queries Once logged in, you can try some simple queries. For example:

mysql> SELECT VERSION(), CURRENT_DATE;+---------------------------+-----------+

| VERSION() | CURRENT_DATE |+---------------------------+-----------+

| 3.23.49 | 2002-05-26| +---------------------------+-----------+

1 row in set (0.00 sec(

Note that most MySQL commands end with a semicolon (;). MySQL returns the total number of rows found, and the total

time to execute the query.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 33: Database Application with MySQL

33

MySQL Command Line Client MySQL Command Line Client

Basic Queries Keywords may be entered in any letter case. The following queries are equivalent:

mysql> SELECT VERSION(), CURRENT_DATE; mysql> select version(), current_date; mysql> SeLeCt vErSiOn(), current_DATE;

Here's another query. It demonstrates that you can use Mysql as a simple calculator:

mysql> SELECT SIN(PI()/4), (4+1)*5; +-------------+-------------+ | SIN(PI()/4) | (4+1)*5| +-------------+-------------+ | 0.707107 | 25 | +-------------+-------------+ 1 row in set (0.00 sec)

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 34: Database Application with MySQL

34

MySQL Command Line Client MySQL Command Line Client

Basic Queries You can also enter multiple statements on a single line. Just end each

one with a semicolon:

mysql> SELECT VERSION(); SELECT NOW(); +------------------+ | VERSION() | +------------------+ | 3.22.20a-log | +------------------+ +---------------------+ | NOW() | +---------------------+ | 2004 00:15:33 | +---------------------+

1 row in set (0.00 sec)

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 35: Database Application with MySQL

35

MySQL Command Line Client MySQL Command Line Client

Multi-Line Commands Mysql determines where your statement ends by looking for the

terminating semicolon, not by looking for the end of the input line.

Here's a simple multiple-line statement:

mysql> SELECT -> USER() -> , -> CURRENT_DATE; +--------------------+------------------------+ | USER() | CURRENT_DATE | +--------------------+------------------------+ | Karwan@localhost | 1999-03-18 | +--------------------+------------------------+ 1 row in set (0.00 sec)

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 36: Database Application with MySQL

36

MySQL Command Line Client MySQL Command Line Client

Canceling a Command If you decide you don't want to execute a command that you are in

the process of entering, cancel it by typing \c

mysql> SELECT -> USER() -> \c mysql>

Using and selecting Database To the select a database, issue the “use” command:mysql> use test;

Show status Reports details of the MySQL DBMS performance and statistics.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 37: Database Application with MySQL

37

Managing Databases Managing Databases The Data Definition Language (DDL) is the set of SQL statements used to

manage a database. Creating Databases

The CREATE DATABASE statement can create a new, empty database without any tables or data.

mysql> CREATE DATABASE webdb;

mysql> use webdb;

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 38: Database Application with MySQL

38

Managing Databases Managing Databases Creating Tables

After issuing the use Database command, you then usually issue commands to create the tables in the database.

Let’s create a table for storing pets. Table: pets

name: VARCHAR(20)owner: VARCHAR(20)species: VARCHAR(20)sex: CHAR(1)birth: DATEdate: DATE

To create a table, use the CREATE TABLE command:

Note: VARCHAR is usually used to store string data…

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 39: Database Application with MySQL

39

Managing Databases Managing Databases mysql> CREATE TABLE pet (

-> name VARCHAR(20), -> owner VARCHAR(20), -> species VARCHAR(20), -> sex CHAR(1), -> birth DATE, death DATE); Query OK, 0 rows affected (0.04 sec)

To verify that the table has been created: mysql> show tables; +------------------------- + | Tables_in_webdb | +------------------------- + | pet | +------------------------- + 1 row in set (0.01 sec)

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 40: Database Application with MySQL

40

Managing Databases Managing Databases Deleting a Table

To delete an entire table, use the DROP TABLE command: mysql> drop table pet; Query OK, 0 rows affected (0.02 sec)

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 41: Database Application with MySQL

41

Managing Databases Managing Databases Show Indexes

Presents the details of all indexes on the table, including the PRIMARY KEY.

SHOW INDEX FROM tablename;

Altering Tables and Indexes

Indexes can be added or removed from a table after creation. To add an index to the customer table, you can issue the following

statement:

ALTER TABLE customer ADD INDEX cities (city);

To remove an index from the customer table, use the following statement:

ALTER TABLE customer DROP INDEX names;

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 42: Database Application with MySQL

42

Managing Databases Managing Databases Displaying Database Structure with SHOW

Details of databases, tables, and indexes can be displayed with the SHOW command.

The SHOW command isn't part of the SQL standard and is MySQL-specific.

Show Data bases

» Lists the databases that are accessible by the MySQL DBMS.

» To get started on your own database, first check which databases currently exist.

» Use the SHOW statement to find out which databases currently exist on the server:

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 43: Database Application with MySQL

43

Managing Databases Managing Databases mysql> show databases; +----------- --+ | Database | +----------- --+ | mysql | | webdb | +------------ -+ 2 rows in set (0.01 sec)

Show tables

» Shows the tables in the database once a database has been selected with the use command.

mysql> show tables; Empty set (0.02 sec)

» An empty set indicates that I had dropped all tables.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 44: Database Application with MySQL

44

Managing Databases Managing Databases Describing Tables

» Shows the attributes, types of attributes, key information, whether NULL is permitted, defaults, and other information for a table.

» To view a table structure, use the DESCRIBE command:

mysql> describe pet;+------- -+------------ +------+---- +------- -+-------+| Field | Type | Null | Key | Default | Extra |+------- -+------------ +------+--- -+------- -+-------+| name | varchar(20) | YES | | NULL | || owner | varchar(20) | YES | | NULL | || species | varchar(20) | YES | | NULL | || sex | char(1) | YES | | NULL | || birth | date | YES | | NULL | || death | date | YES | | NULL | |+------- -+----------- -+---- -+---- +------- -+-------+6 rows in set (0.02 sec)

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 45: Database Application with MySQL

45

Managing Databases Managing Databases » Or use “SHOW COLUMNS FROM tablename“ command to view a

table structure.

mysql> show columns from pet;+------- -+------------ +------+---- +------- -+-------+| Field | Type | Null | Key | Default | Extra |+------- -+------------ +------+--- -+------- -+-------+| name | varchar(20) | YES | | NULL | || owner | varchar(20) | YES | | NULL | || species | varchar(20) | YES | | NULL | || sex | char(1) | YES | | NULL | || birth | date | YES | | NULL | || death | date | YES | | NULL | |+------- -+----------- -+---- -+---- +------- -+-------+6 rows in set (0.02 sec)

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 46: Database Application with MySQL

46

Manipulating Data Manipulating Data The Data Manipulation Language (DML) encompasses all SQL

statements used for manipulating data. There are four statements that form the DML statement set:

» INSERT

» DELETE

» UPDATE

» SELECT

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 47: Database Application with MySQL

47

Manipulating Data Manipulating Data Inserting Data

Having created a database and the accompanying tables and indexes, the next step is to insert data.

Inserting a row of data into a table can follow two different approaches.

» First approach: Use the INSERT statement to enter data into a table. For example:

INSERT INTO pet VALUES ('Fluffy','Harold','cat','f', '1999-02-04',NULL);

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 48: Database Application with MySQL

48

Manipulating Data Manipulating Data »Second approach:

INSERT INTO pet SET Name = 'Fluffy', Owner = 'Harold', Species = 'cat', Sex = 'f', Birth = '1999-02-04', Date = NULL ;

Loading Data to pet table …

The first approach can actually be varied to function in a similar way to the second by including parenthesized attribute names before the VALUES keyword.

INSERT INTO pet (Name, Owner ) VALUES ('Fluffy', 'Harold');

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 49: Database Application with MySQL

49

Manipulating Data Manipulating Data Loading Sample Data

» You could create a text file `pet.txt' containing one record per line.

» Values must be separated by tabs, and given in the order in which the columns were listed in the CREATE TABLE statement.

» Then load the data via the LOAD DATA Command.

pet.txt: Sample Data File ..

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 50: Database Application with MySQL

50

Manipulating Data Manipulating Data Loading Sample Data

» To Load pet.txt:

mysql> LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE pet;

» For each of the examples, assume the following set of data.

loading pet.txt into table pet..

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 51: Database Application with MySQL

51

Manipulating Data Manipulating Data Deleting Data

There is an important distinction between dropping and deleting in SQL.

» DROP is used to remove tables or databases.

» DELETE is used to remove data.

DELETE FROM pet;

DELETE FROM pet WHERE name= ‘claws’;

Deleting ‘Claws’ from table pet..

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 52: Database Application with MySQL

52

Manipulating Data Manipulating Data Updating Data

Data can be updated using a similar syntax to that of the INSERT statement.

UPDATE pet SET owner=‘ali’;

UPDATE pet SET owner= ‘ali' WHERE name = ‘fang’;

Updating table pet…

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 53: Database Application with MySQL

53

Manipulating Data Manipulating Data Querying with SQL SELECT

The SELECT statement is used to query a database and for all output operations in SQL.

» The simplest form of SELECT retrieves everything from a tablemysql> select * from pet;

8 rows in set (0.00 sec)

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 54: Database Application with MySQL

54

Manipulating Data Manipulating Data Selecting Particular Rows

» You can select only particular rows from your table.

» For example, if you want to verify the change that you made to Bowser's birth date, select Bowser's record like this:

mysql> SELECT * FROM pet WHERE name = "Bowser";

1 row in set (0.00 sec)

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 55: Database Application with MySQL

55

Manipulating Data Manipulating Data Selecting Particular Rows

» To find all animals born after 1998 SELECT * FROM pet WHERE birth >= "1998-1-1";

» To find all female dogs, use a logical AND SELECT * FROM pet WHERE species = "dog" AND sex = "f";

» To find all snakes or birds, use a logical OR SELECT * FROM pet WHERE species = "snake" OR species = "bird";

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 56: Database Application with MySQL

56

Manipulating Data Manipulating Data Selecting Particular Columns

» If you don’t want to see entire rows from your table, just name the columns in which you are interested, separated by commas.

» For example, if you want to know when your pets were born, select the name and birth columns.

mysql> select name, birth from pet;

8 rows in set (0.01 sec(

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 57: Database Application with MySQL

57

Manipulating Data Manipulating Data Sorting and Grouping Output

Sorting data (ORDER BY)

» The ORDER BY clause sorts the data after the query has been evaluated. To sort a result, use an ORDER BY clause.

» For example, to view animal birthdays, sorted by date: mysql> SELECT name, birth FROM pet ORDER BY birth;

8 rows in set (0.01 sec(

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 58: Database Application with MySQL

58

Manipulating Data Manipulating Data Sorting and Grouping Output

Sorting data (DESC)

» To sort in reverse order, add the DESC (descending keyword)

mysql> SELECT name, birth FROM pet ORDER BY birth DESC;

8 rows in set (0.01 sec(

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 59: Database Application with MySQL

59

Manipulating Data Manipulating Data Working with NULLs

» To sort in reverse order, add the DESC (descending keyword)

» NULL means missing value or unknown value.

» To test for NULL, you cannot use the arithmetic comparison operators, such as =, < or <>.

» Rather, you must use the IS NULL and IS NOT NULL operators instead.

» For example, to find all your dead pets (what a morbid example!)

mysql> select name from pet where death >IS NOT NULL;

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 60: Database Application with MySQL

60

Manipulating Data Manipulating Data Pattern Matching

SQL Pattern matching

» To perform pattern matching, use the LIKE or NOT LIKE comparison operators.

» By default, patterns are case insensitive.

Special Characters

» _ Used to match any single character.

» % Used to match an arbitrary number of characters.

Note: MySQL providesstandard SQL pattern matching.regular expression pattern matching, similar to those used by Unix utilities such as vi, grep and sed.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 61: Database Application with MySQL

61

Manipulating Data Manipulating Data Pattern Matching Example

To find names beginning with ‘b’:

mysql> SELECT * FROM pet WHERE name LIKE "b%";

To find names ending with `fy':

mysql> SELECT * FROM pet WHERE name LIKE "%fy";

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 62: Database Application with MySQL

62

Manipulating Data Manipulating Data Pattern Matching Example

To find names containing a ‘w’:

mysql> SELECT * FROM pet WHERE name LIKE "%w%";

To find names containing exactly five characters, use the _ pattern character:

mysql> SELECT * FROM pet WHERE name LIKE "_____";

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 63: Database Application with MySQL

63

Manipulating Data Manipulating Data GROUP BY

» The GROUP BY clause is different from ORDER BY because it doesn't sort the data for output. Instead, it sorts the data early in the query process, for the purpose of grouping or aggregation.

SELECT city, COUNT(*) FROM customer

GROUP BY city;

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 64: Database Application with MySQL

64

Manipulating Data Manipulating Data There are several functions that can be used in aggregation with the

GROUP BY clause. Five particularly useful functions are:

» AVG( ): Finds the average value of a numeric attribute in a set.

» MIN( ): Finds a minimum value of a string or numeric attribute in a set.

» MAX( ): Finds a maximum value of a string or numeric attribute in a set.

» SUM( ): Finds the sum total of a numeric attribute.

» COUNT( ): Counts the number of rows in a set.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 65: Database Application with MySQL

65

Manipulating Data Manipulating Data Counting Rows Example

» Databases are often used to answer the question, "How often does a certain type of data occur in a table?“

» For example, you might want to know how many pets you have, or how many pets each owner has.

» Counting the total number of animals you have is the same question as “How many rows are in the pet table?” because there is one record per pet.

» The COUNT() function counts the number of non-NULL results.

» A query to determine total number of pets: mysql> SELECT COUNT(*) FROM pet;

1 row in set (0.01 sec

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 66: Database Application with MySQL

66

Manipulating Data Manipulating Data HAVING

» The HAVING clause permits conditional aggregation of data into groups.

SELECT city, count(*), max(salary)

FROM customer GROUP BY city

HAVING count(*) > 10;

DISTINCT

» The DISTINCT operator presents only one example of each row from a query.

SELECT DISTINCT surname FROM customer;

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 67: Database Application with MySQL

67

Manipulating Data Manipulating Data Join Queries / Cartesian Product

» A join query is a querying technique that matches rows from two or more tables based on a join condition in a WHERE clause and outputs only those rows that meet the condition.

SELECT winery_name, region_name FROM winery, region

ORDER BY winery_name, region_name;

» The query produces all possible combinations of the four region names and 300 wineries in the sample database! In fact, the size of the output can be accurately calculated as the total number of rows in the first table multiplied by the total rows in the second table. In this case, the output is 4 x 300 = 1,200 rows.

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 68: Database Application with MySQL

68

Manipulating Data Manipulating Data Elementary Natural Joins

» A cartesian product isn't the join we want. Instead, we want to limit the results to only the sensible rows.

SELECT winery_name, region_name

FROM winery, region

WHERE winery.region_id = region.region_id

ORDER BY winery_name;

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 69: Database Application with MySQL

69

SummarySummary Is that all there is to MySQL?

» Of course not!

» Understanding databases and MySQL could take us several months(perhaps years!)

» For now, focus on:

» using the MySQL shell with phpMyadmin

» creating database

» creating general and standard SQL queries

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 70: Database Application with MySQL

70

SummarySummary Summary

» SQL provides a structured language for querying/updating multiple databases.

» The more you know SQL, the better.

» The most important part of SQL is learning to retrieve data.

» selecting rows, columns, Boolean operators, pattern matching, etc.

» Keep playing around in the MySQL Shell with phpMyadmin .

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 71: Database Application with MySQL

71

ExampleExample Example. The complete winestore DDL statements

CREATE TABLE wine (

wine_id int(5) DEFAULT '0' NOT NULL auto_increment,

wine_name varchar(50) DEFAULT '' NOT NULL,

winery_id int(4),

type varchar(10) DEFAULT '' NOT NULL,

year int(4) DEFAULT '0' NOT NULL,

description blob,

PRIMARY KEY (wine_id),

KEY name (wine_name)

KEY winery (winery_id)

);

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 72: Database Application with MySQL

72

ExampleExample Example. The complete winestore DDL statements

CREATE TABLE winery (

winery_id int(4) DEFAULT '0' NOT NULL auto_increment,

winery_name varchar(100) DEFAULT '' NOT NULL,

region_id int(4),

description blob,

phone varchar(15),

fax varchar(15),

PRIMARY KEY (winery_id),

KEY name (winery_name)

KEY region (region_id)

);

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 73: Database Application with MySQL

73

ExampleExample Example. The complete winestore DDL statements

CREATE TABLE region (

region_id int(4) DEFAULT '0' NOT NULL auto_increment,

region_name varchar(100) DEFAULT '' NOT NULL,

description blob,

map mediumblob,

PRIMARY KEY (region_id),

KEY region (region_name)

);

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 74: Database Application with MySQL

74

ExampleExample Example. The complete winestore DDL statements

CREATE TABLE customer (

cust_id int(5) NOT NULL auto_increment,

surname varchar(50) NOT NULL,

firstname varchar(50) NOT NULL,

initial char(1),

title varchar(10),

addressline1 varchar(50) NOT NULL,

addressline2 varchar(50),

addressline3 varchar(50),

city varchar(20) NOT NULL,

state varchar(20),

zipcode varchar(5),

country varchar(20),

phone varchar(15),

fax varchar(15),

email varchar(30) NOT NULL,

birth_date date( ),

salary int(7),

PRIMARY KEY (cust_id), KEY names (surname,firstname) );© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 75: Database Application with MySQL

75

ExampleExample Example. The complete winestore DDL statements

CREATE TABLE users (

cust_id int(4) DEFAULT '0' NOT NULL,

user_name varchar(50) DEFAULT '' NOT NULL,

password varchar(15) DEFAULT '' NOT NULL,

PRIMARY KEY (user_name),

KEY password (password)

);

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 76: Database Application with MySQL

76

ExampleExample Example. The complete winestore DDL statements

CREATE TABLE grape_variety (

variety_id int(3),

variety_name varchar(20),

PRIMARY KEY (variety_id),

KEY var (variety)

);

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 77: Database Application with MySQL

77

ExampleExample Example. The complete winestore DDL statements

CREATE TABLE inventory (

wine_id int(5) DEFAULT '0' NOT NULL,

inventory_id int(3) NOT NULL,

on_hand int(5) NOT NULL,

cost float(5,2) NOT NULL,

case_cost float(5,2) NOT NULL,

dateadded timestamp(12) DEFAULT NULL,

PRIMARY KEY (wine_id,inventory_id)

);

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 78: Database Application with MySQL

78

ExampleExample Example. The complete winestore DDL statements

CREATE TABLE orders (

cust_id int(5) DEFAULT '0' NOT NULL,

order_id int(5) DEFAULT '0' NOT NULL,

date timestamp(12),

discount float(3,1) DEFAULT '0.0',

delivery float(4,2) DEFAULT '0.00',

note varchar(120),

PRIMARY KEY (cust_id,order_no)

);

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 79: Database Application with MySQL

79

ExampleExample Example. The complete winestore DDL statements

CREATE TABLE items (

cust_id int(5) DEFAULT '0' NOT NULL,

order_id int(5) DEFAULT '0' NOT NULL,

item_id int(3) DEFAULT '1' NOT NULL,

wine_id int(4) DEFAULT '0' NOT NULL

qty int(3),

price float(5,2),

date timestamp(12),

PRIMARY KEY (cust_id,order_no,item_id)

);

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 80: Database Application with MySQL

80

ExampleExample Example. The complete winestore DDL statements

CREATE TABLE wine_variety (

wine_id int(5) DEFAULT '0' NOT NULL,

variety_id int(3) DEFAULT '0' NOT NULL,

id int(1) DEFAULT '0' NOT NULL,

PRIMARY KEY (wine_id, variety_id)

);

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

Page 81: Database Application with MySQL

81

ENDEND

© University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015

END…END… Any questions..? Any questions..?

Hope you have been happyHope you have been happyThank you Thank you

By: Msc. Karwan M. By: Msc. Karwan M.

KareemKareem20142014 - - 20152015


Recommended