You are on page 1of 88

MySQL Administration

MLMA181-01
MySQL Administration
MLMA181-01V1.0

Compiled by Lance Whyte and Nceba Matandabuzo

Quality assured by Craig Spindler and Johannes Lombaard

Edited by Esmé Grobler, Norman Baines and Ali Parry

Version 1.0

© October 2016 CTI Education Group


Table of Contents

Introduction to MySQL 4
Description 4
Assessment for pass 5
Reference books 6
Structure of a unit 7
Minimum system requirements 8
Icons used in the learning manual 9

Unit 1 – Introduction to MySQL Administration 10


1.1 Basic database concepts 11
1.2 MySQL data directory 14
1.3 General MySQL administration 21
1.4 Test your knowledge 37

Unit 2 – Access Control and Security 40


2.1 Database security 41
2.2 Avoiding access control risks 55
2.3 Setting up secure connections 61
2.4 Test your knowledge 65

Unit 3 – Maintaining a Database 66


3.1 Database maintenance 67
3.2 Database backups 72
3.3 Test your knowledge 79

Glossary 81
Bibliography 83
MySQL Administration - Exercise Checklist 84
MySQL Administration - Evaluation Form 86
Introduction to MySQL

Description
The aim of this module is to show students how to use MySQL Administration
to manage the MySQL open source database.

Students will be introduced to various MySQL components to run the MySQL


server: general MySQL administration; MySQL data directory for securing the
database once it is installed; MySQL maintenance, access control and security
for maintaining the contents of the database.

Students will use MySQL Administration responsibilities to ensure that the


contents of the database are secure so that data can be accessed only by
those who have the proper authorisation. Students will also learn how to
handle various problems and how to prevent them from occurring. In addition,
students will be taught how to create a database backup and implement
recovery and server replication.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 4 of 95


Assessment for pass
A pass is awarded for the module on the achievement of all the pass assessment
criteria.

Learning outcomes Assessment criteria for pass

To achieve each outcome a student must


demonstrate the ability to:

P1.1 Know the location of the data directory.


P1.2 Understand the data directory structure.
1. Understand MySQL
data directory P1.3 Know how to relocate data directory
content.
P1.4 Maintain log files within the data directory.

P2.1 Create a successful MySQL installation.

2. Implement MySQL P2.2 Manage a MySQL database.


administration P2.3 Configure a storage engine.
P2.4 Run MySQL on multiple servers.

P3.1 Use internal security.


3. Implement MySQL
P3.2 Use external security.
database security
P3.3 Set up a secure connection.

P4.1 Perform general database maintenance.


4. Maintain a database P4.2 Create a database backup.
P4.3 Set up a replication server.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 5 of 95


Reference books

The following textbook is required to complete this module:

 DuBois, Paul. 2013. MySQL. Fifth Edition. Pearson


Education.

Supplementary reference books that may be borrowed from


the library for further understanding include:

 DuBois, P., Hinz, S. & Pedersen, C. 2005. MySQL 5


Certification Study guide. MySQL Press.

Additional reference books will be listed at the end of each unit. This
supplementary reading is not mandatory, but it will certainly help you to
answer some of the intermediate and advanced questions in the exams. This
reference material will be a great aid if you would like to know more or gain a
different perspective on what you have learnt in this module.

How to approach this module?


This module is divided into three units. Each unit consists of:

 Theory (short, medium and long questions)


 Examples
 Exercises

A theory exam will be written at the end of the module. Ensure that you know
and understand the theory before continuing with an exercise or exam.
Everyone wants to get their hands dirty as soon as possible with regard to
actual programming, but there will be many opportunities to practise what you
have learnt. Work through the examples in the reference book and complete
all the exercises before attempting the project and exam. Application questions
will be asked in the exam and you must be able to apply your knowledge to
practical situations.

You will not pass the examination if you rush through the material without
understanding what you have learnt. The examinations are designed to test
theory, insight and practical skills. Theory examinations will consist of one
word, multiple choice, code analysis, and long definition/summary questions.
It is very important to use all the study aids available to you. Some of the
questions in the examinations will test your general knowledge on advanced
subjects that may not have been covered in the learning manual, although the

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 6 of 95


content in the learning manual will be sufficient to ensure that you pass each
unit.
Take note that each unit builds on previous units. Exams will cover all the
material with which you should be familiar. The module is divided up as
follows:

Table 1 – Module breakdown

Section Unit % Notes

Unit 1 Reading and exercises

Unit 2 Reading and exercises

Unit 3 Reading and exercises

Theory
100% Theory examination covering all the
exam work.

Structure of a unit
This module can be completed on the Windows platform of the distributions
offered at your campus. This depends on which platform is mainly used for the
qualification that you are doing. The learning process of the module will require
you to complete exercises as you progress through the module material. After
completion of each unit, you also have to complete a compulsory ‘Test Your
Knowledge’ section before continuing with the next unit.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 7 of 95


Minimum system requirements
Hardware requirements
 800 MHz Intel Pentium III Processor (or equivalent) and later
 1 GB RAM
 DVD-ROM
 Internet connection (optional)
 1024 x 768, 16-bit display
 20 GB of available disk space

Software requirements
 Windows 10 or Linux Ubuntu
 MySQL-community 5.7.6 -winx86,32 (can be downloaded)
 MySQL-workbench-CE-6.3- x86, 32 (comes with MySQL 5.7.6 bundled or
can be installed independently)

Font guide
 Examples of source code and commands that should be entered will be
printed in a box as shown below:

This is how examples of source code and output look.

This is how examples of console output look.

 URLs will be underlined:

http://www.mysite.com/index/

 File and path names will be printed in bold:

Open the sampdb.sql file.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 8 of 95


Icons used in the learning manual

Denotes the start of each main subsection in the learning manual.

Denotes the start of each subsection in the learning manual.

Denotes the outcomes of the unit, i.e. the knowledge and skills
that you should have acquired after each section.

Points out the keywords of each section. Ensure that you can
name and explain all the keywords before proceeding to the next
section.

Recommended exercises for each section.

Test your understanding. Answers to these revision questions are


provided in the Lecturer Guide.

Indicates required reading from the textbook.

Indicates supplementary reading from other sources that you can


use to broaden your knowledge.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 9 of 95


Unit 1 – Introduction to MySQL Administration

The following topics will be covered in this unit:

 Introducing MySQL administration


 MySQL data directory
 General MySQL administration

Read through the following tutorial:

DuBois, Paul. 2013. MySQL. Fifth Edition. Pearson Education.


Chapters 10, 11, 12.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 10 of 95


1.1 Basic database concepts

This is a brief overview of some basic database concepts, to refresh your


memory.

By the end of this subsection you will:

 Have knowledge of the administration background.


 Understand the various MySQL components.
 Understand the general MySQL administration operation.

1.1.1 Introducing MySQL administration


MySQL administration concerns the duties involved in administering MySQL
installations, as well as the requirements needed to maintain a database to
ensure that it operates smoothly and efficiently.

NOTE For the installation process of MySQL and MySQL Workbench, refer
to the MySQL Development Guide.

1.1.2 MySQL components


The MySQL database system is made up of several components. You should be
familiar with these components and their purpose. If you understand the
components, it will make the work much easier.
Aspects of MySQL:

 MySQL server: mysqld is the main server program used and it is the hub
of the MySQL installation. It is also used to perform all manipulations of
databases and tables. The server utilises the mysqld_multi when running
multiple servers on a single host. This helps you manage the servers more
easily.

 MySQL clients and utilities: The following is a list of MySQL programs


that communicate with the server:
o mysql – An interactive program used to send SQL statements to the
server and to view the results. It is also used to execute batch scripts
(text files containing SQL statements).

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 11 of 95


o mysqladmin – An administrative program used to perform tasks such
as shutting down the server, checking its configuration or monitoring its
status.

o mysqldump and mysqlhotcopy – Tools used for backing up your


databases or copying databases to another server.

o mysqlcheck and myisamchk – Programs used for table checking,


analysis and optimisation, as well as table repairs. Both programs work
with the MyISAM tables, but mysqlcheck works with InnoDB and other
engines as well.

 MySQL data directory: This is where the server stores its databases and
status files.

1.1.3 General MySQL administration


General MySQL administration deals with the operation of mysqld, the MySQL
server, and provides the users with access to the server.

The following duties are most important in carrying out MySQL administration:

 Server start-up and shutdown


 User account maintenance
 Log maintenance
 Server configuration and tuning: multiple server management

NOTE We will discuss the above list in more detail later on in the module.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 12 of 95


1.1.4 Key terms
 mysql
 mysqladmin
 mysqldump
 mysqlhotcopy
 mysqlcheck
Myisamchk

1.1.5 Exercises

Ensure MySQL server and Workbench are installed and


running correctly. Consult your MySQL Development Guide for
any queries and guidelines.

1.1.6 Revision questions

1. What is the main server program used in MySQL?

2. Which server is used when running multiple servers?

3. A program used for shutting down the server is called


_________?

4. Where are databases and status files stored on the


server?

5. List three duties an administrator is responsible for.

1.1.7 Suggested reading


DuBois, Paul. 2013. MySQL. Fifth Edition. Pearson Education.
ISBN: 9780321833877.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 13 of 95


1.2 MySQL data directory

By the end of this subsection you will:


 Understand the concept of the MySQL data directory.
 Understand the structure of the data directory.

1.2.1 Location of the data directory


A default data directory location is compiled into the server. In Windows, the
default data directory location is: C:\Program Files\MySQL\MySQL Server
5.7\data or C:\mysql\data.

The following are some of the command-line options used for the data
directory:
Table 1.0 – Command-line option

Command-line option Description

--localstatedir=dir_name Used to designate the default data


directory location, if MySQL is
compiled from source

--datadir=dir_name Specifies the data directory location at


server start-up

The following option can be used to locate the data directory should you not
know its location, and the server is running:

mysql> SHOW VARIABLES LIKE 'datadir';

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 14 of 95


Figure 1.0 – Show the location of the data directory

1.2.2 Structure of the data directory


Databases managed by the server are all stored in the MySQL data directory,
which is organised into a tree structure. This tree structure utilises the
hierarchical structure of the Windows file system.

The structure is set out as follows:

 Each database has a database directory located under the data directory.
 Tables, views, and triggers within a database correspond to files in the
database directory.

Data directories do not only store databases, but other files as well, such as:

 The server’s process ID (PID).


 Status and log files generated by the server.
 Server-related files, such as the DES key file or the server’s SSL certificate
and key files.

1.2.2.1 How MySQL provides access to data


The MySQL server mysqld acts as a single entity to manage all databases in
the data directory. Client programs do not manipulate data directly. Instead,
the server provides the only point through which databases are accessed.
How the architecture works:
 A network interface to the data directory is presented to listen for various
types of network connections when the server starts.
 To access data, a client program establishes a connection to the server, and
communicates requests as SQL statements.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 15 of 95


 The server performs each operation requested in the SQL statement and
sends back the result to the client.

Advantages of using a single server to access data:

 The server is multi-threaded – This means that it can service multiple


simultaneous client connections.
 The server serialises requests – This prevents two clients from changing a
given row at exactly the same time.

There are times when the server does not have full control of the data
directory:

 When multiple servers are run on a single data directory.


 When direct-access maintenance utilities are used.

1.2.3 MySQL status and log files


The MySQL data directory contains status and log files in addition to database
directories.

Below is a list of the server-level status and log files created:

Table 1.1 – Server level status and log files

File Type Default Name Description

Error log HOSTNAME.err Start-up, shutdown events


and error conditions

General query log HOSTNAME.log Connect/disconnect events


and statement information

Process ID file HOSTNAME.pid Server process ID

Binary log HOSTNAME-bin.nnnnnn Binary representation of


statements that modify
data

Binary log index HOSTNAME-bin.index List current binary log files

Relay log HOSTNAME-relay- Data modifications received


bin.nnnnnn by slave server from master

Relay log index HOSTNAME-relay- List current relay log files


bin.index

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 16 of 95


Master info file master.info Parameters for connecting
to master server

Relay info file Relay-log.info Status of relay processing

Slow-query log HOSTNAME-slow.log Text of statements that


take a long time to process

NOTE HOSTNAME denotes the default name and nnnnnn denotes a


numbered sequence file for binary and log files.

1.2.4 Relocating data directory contents


MySQL allows the user to relocate the data directory by itself or by certain
elements within it.

Reasons for relocating the data directory:

 Insufficient filesystem space.


 Improved performance by locating the data directory on a less active drive.
 Improved security by placing the database on one disk and the logs on
another; this helps to minimise the damage caused should a single disk
failure occur.
 Eliminated pre-process file descriptor limits while running multiple servers
with its own data directory.

There are many ways of changing the data directory:

1. Changing the data directory using physical file relocation:

Here we follow the following steps:

o (Start>Administrative Tools>Services) and stop the MySQL57 service.


o Open C:\Program Files (x86)\MySQL\MySQL Server 5.7\my-
default.ini (or my.ini) depending on version on MySQL and the
installation path.
o Open the my-default.ini (or my.ini) with notepad/notepad++ and
modify the labelled entry “basedir=” to
“datadir=D:\MySQL\NewLocation\Data\”
o Save the my-default.ini (or my.ini) file
o Create the D:\MySQL\NewLocation\ folder. Do not create the Data sub
folder.
o Copy the C:\ProgramData\MySQL\MySQL Server 5.7\Data into
D:\MySQL\NewLocation\ folder.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 17 of 95


o Start the MySQL57 service and you are good to work on you new
location.

2. Use MySQL Workbench to relocate the files.

 Log on to your MySQL Workbench account.


 Go to Server tab> Options File>General tab>Directories>Datadir and set
the path to the folder on your D drive or other drive; then click Apply to
apply changes to MySQL configuration file.
 Then copy over the Data from the initial location to the new location, i.e. as
in method 1 above.
 Now, on MySQL Workbench>Under Instance, Start/Shutdown MySQL
Server> click Stop Server.
 Rename the existing old Data Files location, i.e.
C:\ProgramData\MySQL\MySQL Server 5.7\Data to
C:\ProgramData\MySQL\MySQL Server 5.7\Data-OLD and re-launch MySQL
Workbench and go to Under Instance, Start/Shutdown MySQL Server> click
Start Server and provide a password if prompted.
 Now MySQL should be running in the new directory as a default.

It is common to find an error when accessing Option Files, Server Logs,


Startup/Shutdown, Server Status. If you encounter an error preventing you
from performing the above-mentioned steps, you will need to uninstall MySQL
completely. Before you uninstall completely ensure that your database script
files are saved somewhere.

3. Use command-line options

The command-line option method is similar to the physical file relocation


except that here we work with commands. Here, our first step is to find the
“.ini” file. At times it may not be easy to find the “.ini” file like in method 1
above; in such a case we use the following command:
 By using the command below in Figure 1.1, we get to know the name of
the file we are looking for, its location, date created or last modified, and
its size.
 Now all we need to do is to follow the steps mentioned in the physical file
relocations.
 After all the steps have been completed successfully, the server should
start normally and you are ready to work on your new directory
environment.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 18 of 95


Figure 1.1 – Show the location of the data directory file (.ini)

http://www.gunnalag.com/2014/05/09/relocate-or-move-mysql-on-windows-
data-files-to-another-drive-using-mysql-workbench/

http://dba.stackexchange.com/questions/24403/change-existing-datadir-path

To relocate the data directory or elements within it, use the following:

--datadir=dir_name

This can be specified at server start-up on the command-line.

Or

[mysqld]

datadir=dir_name

Enter the above instruction in an option file.

NOTE Caution: Ensure you back up your data, and issue a FLUSH TABLES
statement to close all open table files. Failure to observe these
precautions can result in table damage.

1.2.4.1 Relocating individual databases


In order to relocate a database, a method called the symlink method has to be
used. The reason why we only use this method is that the server always looks
for database directories in the data directory.

The following steps are involved when relocating a database:

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 19 of 95


1. Ensure the server is not running.
2. Move the database directory to its new location or copy and remove the
original database directory.
3. In the MySQL data directory, create a file that will act as a symbolic link.
This will let the MySQL server know where to find the relocated database
directory. Remember to include a database name and to have the file
extension .sym when creating a file.

Example:

C:\mysql\data\worlddb to E:\mysql-country\worlddb

4. Before restarting the server, ensure that the symbolic link is enabled. If it
is not enabled by default in Windows, you can explicitly enable it by using:

--symbolic-links

This can be specified on the command-line.

Or

[mysqld]
Symbolic-links

Enter the above in an option file.

NOTE An entire data directory can also be relocated. Use the same steps
as above, but when the server needs to be restarted, use
the -datadir option to restart the server.

1.2.5 Key terms


 Data directory
 PID
 Status files
 Log files

1.2.6 Exercises
Create a school database with student details and
examinations.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 20 of 95


1.2.7 Revision questions

1. True/False? A default data directory is compiled into the


server.

2. What is the following option used for?

mysql> SHOW VARIABLES LIKE 'datadir';

3. How is the structure of the data directory set out?

4. What are the advantages of using single servers to access


data?

5. The _______ method is used to relocate a database.

1.2.8 Suggested reading

DuBois, Paul. 2013. MySQL. Fifth Edition. Pearson Education.

http://www.gunnalag.com/2014/05/09/relocate-or-move-
mysql-on-windows-data-files-to-another-drive-using-mysql-
workbench/

http://dev.mysql.com/doc/refman/5.7/en/option-files.html

1.3 General MySQL administration


By the end of this subsection, you will be able to:

 Secure a MySQL installation.


 Tune a server.
 Maintain a database.
 Maintain log files.
 Configure a storage engine.
 Run multiple servers.

1.3.1 Secure a new MySQL installation


During the installation process, MySQL installation sets up the server’s data
directory and populates it with two databases:

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 21 of 95


A mysql database – this contains the grant tables used to control access by
clients to the server.

A test database – this is a database used for testing purposes.

In order to secure a MySQL installation, a password should be set up at


installation. This will prevent anyone from connecting to the server without a
password.

1.3.1.1 Establishing passwords


The grant table, which is set up during the installation process, is created with
two kinds of accounts:

 Accounts that have a username or root – used for administrative purposes.


 Accounts that have a blank username – enables users to connect to the
server without having accounts set up; this account usually limits the
privileges available to the user.

To check what accounts are present and if they have passwords, use the
following:

%mysql –u root

mysql> SELECT User, Host, HEX(authentication_string) FROM mysql.user;

mysql> SELECT Host, User, Password FROM mysql.user; #Previous versions of MySQL

This has changed from previous versions of MySQL that are using the last
statement with the word password, including the word password in your
query for MySQL 5.7.6 onwards which will issue an error message.

Figure 1.2 – Output for accounts and their passwords

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 22 of 95


Here, all user accounts have passwords and the DBAdmin account can use
both localhost and remote host resources.

The statement uses HEX() because passwords stored in the


authentication_string column contain binary data that does not display well.

NOTE If there are any hosts with blank passwords, assign them passwords.
You will learn in the next unit why accounts with no passwords must
be assigned passwords.

The following statements can be used to set the root and anonymous user
passwords for a specific account:

mysql>SET PASSWORD FOR 'root'@'localhost' = PASSWORD ('pumpkin');

Or

mysql>SET PASSWORD FOR ' ' @'localhost' = PASSWORD ('apass');

An alternative to SET PASSWORD is to use the UPDATE statement to modify


the user table directly to specify a password for all accounts with a given user
value. This allows you to modify multiple accounts simultaneously:

mysql>UPDATE mysql.user SET PASSWORD=PASSWORD ('pumpkin') WHERE User= 'root';


mysql>UPDATE mysql.user SET PASSWORD=PASSWORD ('apass') WHERE User='';
mysql>FLUSH PRIVILEGES;

The FLUSH PRIVILEGES in the above statement tells the server explicitly to
reload the tables. This is done because you have added a password which
alters the grant tables. FLUSH PRIVILEGES only has to be used with UPDATE
as SET PASSWORD automatically tells the server to re-read the grant tables
and refresh its in-memory copy of the tables.

It is possible to remove account privileges by using the following:

mysql>REVOKE ALL ON *.* FROM ‘’@’localhost’;

Should you have no need for anonymous user accounts, it is recommended


that they are removed with the following:

mysql>DROP USER ''@'localhost'

Once you have a password set up, use the following to connect to the server:

%mysql –p –u root
Enter password: snoopy
mysql> "this line indicates the server is running"

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 23 of 95


1.3.2 Maintain log files
As mentioned earlier, the MySQL server can create several log files. These log
files are used to diagnose problems, improve server performance, enable
replication and manage crash recovery.

The following table lists the log files available and their uses:

Table 1.2 – Log files

Log Description

Error log This is the place to look when the server fails to
start. This log contains a record of server start-up
and shutdowns as well as problem or exceptional
messages. Before the server terminates, the server
writes an error message into the log.

General query log When it comes to troubleshooting or debugging, this


log file is the most convenient log to use. General
query log files store records of client connections,
SQL statements received from clients, and any other
events related to client connections.

Slow query log If a statement takes longer than 10 seconds (by


default) to execute, it is deemed a slow query and
written to the log. This helps you to identify
statements that are needed to be rewritten for
better performance. Queries with no indexes are
also written to the log file.

Binary log Used to log any modifications performed by


UPDATE, DELETE, INSERT, CREATE TABLE, DROP
TABLE, GRANT commands. Binary logs have two
purposes:

 May be used in conjunction with backups to


restore tables after a crash.

 Stored data modification events are transmitted


to replication slave servers.

Binary log index Accompanies the binary log to list which binary log

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 24 of 95


files exist on the server.

Relay log Relay logs are used only if the server acts as a
replication slave. Records are stored if data
modification events, received from the master, need
to be executed.

Relay log index Accompanies the relay log to list which relay log files
exist on the slave.

NOTE For the purpose of this module, you will not need to know how to
create log files, but merely have an understanding of the different
types of log files used by the server.

1.3.2.1 Log management


It is important to keep and create log files. However, one disadvantage of
logging is that it has the potential to fill up disk space. This is due to the huge
amounts of information generated during the logging process.

The following methods are used to manage logs and prevent them from
growing without bounds:

 Log rotation – Used for log files which have a fixed name, i.e. general and
slow query log files.
 Age-based expiration – Any logs older than a certain age are removed
using this method, i.e. log files created in a numbered sequence like binary
logs. If the binary log is used for replication, this method should not be
used.
 Replication-related expiration – Any binary log files used for replication
should ideally be expired only when they have been sent completely to
each slave and not based on the age of the log.
 Log table truncation or rotation – Empty tables can be used to replace,
truncate, or rename tables in the MySQL database. Log rotation is used in
conjunction with log flushing by issuing the following command: FLUSH
LOGS.

Log files should not be expired before they have been backed up. This will
ensure you have a copy should a recover operation be required.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 25 of 95


1.3.3 Tuning the server
The MySQL server operates by using various system variables, known as
parameters. Most system variables can be set in option files or at server start-
up using the command line options. The ability to set the system variables
gives the client a measure of control over how the server operates and this
allows them to customise the behaviour of the server.

System variables can exist at two levels:

 Global – These variables affect the operations of the server as a whole.


 Session-specific – These variables only affect how the server treats a
given client connection.

The only time a system variable can exist at both levels is when a new client
connection begins. When this occurs, the global variable is used to initialise the
corresponding session variable.

To view which variables the server is using, issue the following statement:

mysql>SHOW VARIABLES

Figure 1.3 – Result from the SHOW VARIABLES statement

Three main groups of system variables are used by the server:

 Performance tuning variables – These variables are responsible for


controlling the size of memory buffers.
 Client interaction variables – These variables affect the way in which the
server interacts with clients, i.e. variables which control the SQL mode, the
default storage engine, and the current time zone.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 26 of 95


 Status variables – These variables provide information about the server
performance when it is running. The information displayed helps monitor
the server and checks the effect of configuration changes.

Issue the following statement to display the status variables:

mysql>SHOW STATUS;

Figure 1.4 – Result from the SHOW STATUS statement

1.3.3.1 Setting system variables


System variables can be set at either server start-up time or during runtime.
The syntax used to set the system variables at start-up is as follows:

%mysql –-max_connections=200

Or

[mysqld]
max_connections=200

The syntax used to set the system variables at runtime is:

SET GLOBAL var_name = value;

Or

SET @@GLOBAL var_name = value;

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 27 of 95


Figure 1.5 – Result from set system variable at runtime

It is also possible to set a session variable at runtime.

Use the following syntax to set a session variable:

SET SESSION var_name = value;

Or

SET @@SESSION var_name = value;

NOTE The keyword LOCAL is a synonym for SESSION.

If no level indicator is present, i.e. global or session, then the SET statement
will be the following:

SET var_name = value;


SET @@var_name = value;

If you want to specify several variables in a single SET statement, ensure they
are separated by commas:

SET SESSION sql_warnings = 0, GLOBAL storage_engine - InnoDB;

Or

If multiple variables need to be set, an explicit GLOBAL or SESSION level


indicator is required:
SET SESSION v3 = val3, v4 = val4, GLOBAL v5 = val5, v6 = val6;

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 28 of 95


NOTE In order for a GLOBAL variable to be set, you must have SUPER
privileges. This setting lasts until new changes have been executed or
the server exits.

1.3.3.2 Log control at run time


The system variables associated with log tables and files are allowed a runtime
control over logging:

 The global log_output system variable indicates the destination of the


current logging.
 Global general_log_file and slow_query_log variables indicate whether the
general query log and slow query log are enabled or disabled. These
variables can be set at runtime to check whether logs are enabled.
 Global general_log_file and slow_query_log_file variables indicate the names
of the general query log and slow log files. The variables can be set at server
start-up or at runtime to change the names of the log files.

Benefits of using tables for log output:

 Log entries have a standard format. To display the current structure of the
log tables, use this statement:

SHOW CREATE TABLE mysql.general_log;


SHOW CREATE TABLE mysql.slow_log;

 Log contents are accessible through SQL statements. This allows the use of
queries that select only log entries to satisfy a specific criterion.
 Logs are accessible remotely through any client that can connect to the
server and issues queries.

Figure 1.6 – Current log table structure

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 29 of 95


 The primary purpose of the log tables is to provide an interface for users to
observe the runtime execution of the server, not to interfere with it at
runtime.
 Log tables use the CSV storage engine as a default which writes data in
comma-separated values format.
 The log tables can be altered to use the MyISAM storage engine. The log
must be disabled first; then you can use ALTER TABLE to alter a log table in
use. No engines other than CSV and MyISAM are legal for log tables.

1.3.3.3 Some log operations


Log operations are used to keep track of table and database data throughout
the life of a database system. This allows the database administrator to have
overall control of the databases by ensuring that operations of the database
are running smoothly as required and that data corruption is prevented where
possible.

 TRUNCATE TABLE: is a valid operation on a log table. It is used to expire or


delete log entries.
 CHECK TABLE: is a valid operation on a log table.
 RENAME TABLE: is a valid operation on a log table.
 LOCK TABLES: cannot be used on a log table.
 INSERT, DELETE and UPDATE: cannot be used on a log table. These
operations are permitted only internally to the server itself.

1.3.4 Storage engine configuration


When working with storage engines the MySQL server provides control over
which storage engines are available.
When deciding which storage engines are available, some of the following
options are available:

 Optional storage engines can be determined if you build MySQL from


source.
 At start-up, some optional storage engines can be enabled or disabled. This
is useful to reduce server memory requirements. However, if you disable a
storage engine, you cannot access any tables which have been created by
the storage engine.
 Available storage engines as well as the default storage engine can be
determined at runtime.

Some of the storage engine configurations and runtime options are:

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 30 of 95


Table 1.3 – Storage engine and runtime options

Storage engine Configuration option Runtime option

ARCHIVE --with-archive-storage- --skip-archive


engine
--without-archive-storage-
engine
Falcon --with-falcon-storage-engine --skip-falcon
--without-falcon-storage-
engine
InnoDB --with-innodb --skip-innodb
--without-innodb

MyIASM Always built Always enabled

MEMORY Always built Always enabled

MERGE Always built Always enabled

Use the configuration option if building MySQL from source; otherwise use the
runtime option.

Use the following commands to display storage engine options:

 To see which engines can be built:

% ./configure --help

 At runtime, to display which options enable or disable engines:

%mysqld –verbose --help

 At start-up, to select a default storage engine:

--default-storage-engine=engine_name

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 31 of 95


If you are unsure which storage engines are available, issue the SHOW
ENGINES statement.

1.3.5 Running multiple servers


When you initially install MySQL, it is run on a single server. However, there
are benefits in running the MySQL server on multiple servers.

Below is a list of some of the benefits of multiple servers:

 Different server binaries can be run. This allows you to test a new version of
the server, while leaving the production server undisturbed.
 You are able to familiarise yourself with replication on a separate server, as
opposed to only using a single server to run the master and slave.
 Running multiple servers allows you to work around pre-process limits
imposed on open-file descriptors by the operating system you are working
on.
 Multiple servers are required by Internet server providers as they provide
individual customers with their own MySQL installation.
 Multiple servers allow you to start and stop them on demand.

1.3.5.1 Multiple server issues


When multiple servers are run, you need to keep each server separate from
the other to stop them interfering with one another. Some issues which may
occur:
 During installation – Each MySQL version must be placed into a different
location.
 At runtime – Unique values for several parameters must be set for every
server process when you start the server. This will prevent the servers from
colliding when listening for incoming connections on the TCP/IP port.

The following options are used to specify values explicitly to prevent multiple
server issues from occurring:

 If you are running different server versions and need to install each
distribution under a different base directory:

Table 1.4 – Options for running different server versions

Option Purpose

--basedir=dir_name Pathname to root directory of MySQL


installation.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 32 of 95


--datadir=dir_name Pathname to data directory.

 For network interface options to prevent multiple servers from listening on


the same interface, each server must have different values:

Table 1.5 – Options for network interfaces

Option Purpose

--port=port_num Port number for TCP/IP connections.

--socket=file_name Windows named-pipe name.

--shared-memory-base- Name of shared memory to use for shared-


name=name memory connections. Used for Windows
only.

1.3.5.2 Running multiple servers on Windows


When running multiple servers on Windows, two methods can be used:

 Starting the servers manually


 Using multiple Windows services

Below is an example of using the method to start the servers manually:

The given scenario is for running two servers that use the same program
binaries but have different data directories.

1. Create an option file for each server.

C:\my.ini1 file:
[mysqld]
basedir=C:/mysql
datadir=c:/mysql/data1
port=3306

C:\my.ini2 file:
[mysqld]
basedir=C:/mysql
datadir=c:/mysql/data2

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 33 of 95


port=3307

Creating the two data directories will ensure that the data directories exist
before the server can start. If you have already installed MySQL, the first data
directory will automatically be created.

If no server is running, use the following command to create the second data
directory:

C:\>xcopy C:\mysql\data C:\mysql\data2 /E

The above command creates a copy of the C:\mysql\data directory.

2. Start the servers from the command-line using the following:

C:\>mysqld –-defaults-file=C:\my.ini1
C:\>mysqld –-defaults-file=C:\my.ini2

The following options are alternative ways to run multiple servers:


 Using the port numbers. This method uses the mysqladmin for shutting
down the servers.

C:\>mysqladmin –p –u root shutdown


C:\>mysqladmin –p –u root 3307 shutdown

 If you want to install a MySQL server as a Windows service:

C:\>C:\mysql\bin\mysqld --install
C:\>C:\mysql\bin\mysqld –install service_name

 If you want to run two instances of mysqld, using service names and the
same data directories, use the following commands:

# ("MySQL") service name


[mysqld]
basedir=C:/mysql
datadir=c:/mysql/data1
port=3306
shared-memory
shared-memory-base-name=MySQL

# ("mysqlsvn2") service name

[mysqld]
basedir=C:/mysql
datadir=c:/mysql/data2
port=3307
shared-memory
shared-memory-base-name= mysqlsvn2

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 34 of 95


In the given scenario, the first service name, MySQL, will only read the
[mysqld] option. But the second service name, mysqlsvn2, will read both the
[mysqld] and [mysqlsvn2] groups. This allows the second service name to
override all the options in the first service name, but only if it is placed second
in the option file.

From the above, use the following to install and run the service:

C:\>C:\mysql\bin\mysqld --install
C:\>net start MySQL
C:\>C:\mysql\bin\mysqls –install mysqlsvn2

C:\>net start mysqlsvn2

To shut down the servers, use the mysqladmin command as mentioned earlier,
but use the following command to uninstall the services.

c:\> sc delete [MySQL] # where [MySQL] is the service name.

Ensure the services are not running before you execute the
NOTE
above command.

You can visit the MySQL website for more details:

http://dev.mysql.com/doc/refman/5.7/en/multiple-
windows-services.html

1.3.6 Key terms


 FLUSH PRIVILEGES
 UPDATE
 SET PASSWORD
 Log files
 Log rotation
 Age-based expiration
 Replication-related expiration
 Global
 Session-specific
 System variables
 Storage engine

1.3.7 Exercises

In this exercise you are required to run multiple servers on


your machine and test them.

1.3.8 Revision questions

1. Name two accounts used when setting up grant tables.


MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 35 of 95
2. What is the function of the following command?

mysql>SET PASSWORD FOR ' ' @'localhost' = PASSWORD


('apass');

3. Name four advantages of using log files.

4. True/False? System variables can exist at two levels:


global and port-specific.

5. List two benefits of using multiple servers.

1.3.9 Suggested reading

DuBois, Paul. 2013. MySQL. Fifth Edition. Pearson


Education. ISBN: 9780321833877. Chapters 10, 11, 12.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 36 of 95


1.4 Test your knowledge

NOTE The following questions must be completed and handed in to your


lecturer to be marked.

1.4.1 Revision questions

1. True/False? MySQL administration ensures that a database operates


smoothly and efficiently.

2. True/False? mysqladmin is the main server used and it is the hub of the
MySQL installation.

3. Which one of the following MySQL programs is used as an interactive


program to send SQL statements to the server and to view the results?

A. mysql
B. mysqladmin
C. mysqldump
D. mysqlcheck

4. List three duties to be performed when carrying out MySQL administration.

5. True/False? A default data directory location is not compiled into the


server.

6. Which types of files can a data directory store?

A. PID
B. Status and Log files
C. Server related files
D. Format files
E. Command files

7. What is the correct order in which the MySQL architecture works?

i. A network interface to the data directory is presented to listen for


various types of network connections when the server starts.
To access data, a client program establishes a connection to the
server, and communicates requests as SQL statements.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 37 of 95


ii. To access data, a client program establishes a connection to the
server, and communicates requests as SQL statements.

iii. The server performs each operation requested in the SQL statement
and sends back the result to the client.

A. i, ii, iii
B. ii, i, iii
C. iii, ii, i
D. i, iii, ii

8. True/False? The server always has full control over the data directory.

9. Match the columns in the following table.

General query
A. Start-up, shutdown events, and error conditions
log

B. Data modifications received by slave server from


Error log
master

C. Parameters for connecting to master server Relay log

D. Text of statements that take a long time to process Binary log

Slow query log

Master info file

10. What happens if you do not close all open tables before you relocate a
data directory?

11. What can be used to explicitly tell the server to reload the tables?

A. FLUSH PRIVILEGES
B. GRANT TABLES
C. UPDATE PRIVILEGES
D. MODIFY TABLES

12. Once you have a password set up, what command will be issued to start
the server?

13. Match the columns in the following table:

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 38 of 95


1. Used for log files which have a fixed name A. Log table truncation

2. Any logs older than a certain age are B. Replication-related


removed via this method expiration

3. Empty tables can be used to replace,


truncate, or rename tables in the mysql C. Log rotation
database

4. Any binary log files used for replication D. Age-based expiration

14. System variables can be set at either ___ (a) ___ time or during __ (b)
___.

15. What is the function of the following command?

% ./configure --help

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 39 of 95


Unit 2 – Access Control and Security

The following topics will be covered in this unit:

 Understanding internal security


 Using external security
 Using MySQL grant tables

NOTE In the examination, application questions will be asked where students


will need to be able to apply their knowledge of the concepts covered
in this unit.

Read through the following tutorial:

DuBois, Paul. 2013. MySQL. Fifth Edition. Pearson


Education. Chapter 13.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 40 of 95


2.1 Database security

At the end of this subsection you will be able to:

 Use new MySQL Workbench features.


 Understand the MySQL security features.
 Understand the function of internal security.
 Use external security.
 Implement grant tables.

2.1.1 What is new in MySQL Workbench 6.3?


This section explains some new features in MySQL Workbench 6.3. Some of
these existed in 6.0 and 6.1 versions of MySQL Workbench and the 6.3 version
is not much different from 6.1.

 The new home screen: MySQL Workbench home screen of 6.0 and 6.3 is
very different from 5.2 and previous versions. The new home screen has no
SQL Development, Data Modelling and Server Administration workspaces.
It mainly consists of MySQL Connections which is the server connection.
This feature allows setting as many connections as you may need by
clicking the + sign.

 On the far right there is a shortcuts pane with: MySQL Doc Library, MySQL
Utilities, Database Migration, MySQL Bug, MySQL Blogs, etc. The Doc
library shows a documentation comparison of new and old feature. You can
explore other shortcuts to view what is in store.

 Fast Data Migration: This new fast migration was added to the migration
wizard. This is another way to transfer data from one MySQL server to
another while performing a migration, and it complements the existing
solutions. The assumption is to use a generated script on the source server
to create a dump that you move to the target machine to perform the
import there. This avoids the need to traffic all data through MySQL
Workbench, or have a permanent network connection between the servers.
Instead, the dump and restore is performed at maximum speed by using
the LAD DATA call for MySQL import. The migration wizard automatically
creates all necessary scripts for all supported platforms and servers.

 SSL Certificate Generator: A new SSL (Secure Sockets Layer) certificate


generation was added. It helps create proper SSL certificates for both
MySQL clients and MySQL servers. Connections in MySQL Workbench are
updated with the certificates by the wizard. This wizard requires OpenSSL
to create the certificates.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 41 of 95


 SQL Editor Auto-Completion: This feature improves the following:

o It now works with all statement types, when before only SELECT
statements were fully supported.
o It now minds the MySQL server version. For example, it now only shows
the engines available from the server.
o New graphics, including colour-coded (and tagged entries).
o Improved MySQL 5.7 support.

 Geometry Data Viewer: The SQL field and form editors were updated to
support the GEOMETRY datatype. You can view geometry data, such as
polygons, from a single row of an image or as text.
 Execute SQL Scripts: The new Run SQL Script dialog executes an SQL
script without loading it into the SQL Editor. This is useful because loading
large scripts for editing can cause performance problems related to
increased memory usage and required processing for editor features such as
syntax highlighting and code folding. To use this feature, select File menu|
Run SQL Script from file.
 Unified SQL Editor and Administration interface: The Server
Administration is now accessible directly from the SQL Editor interface,
located near where the schema information can be browsed and queries
executed; see Figure 2.0:

Figure 2.0 – SQL Editor interface

The negotiator pane will be located on the left side of the opened connection
window.

 Table data search: you can search schemas and tables to perform client-
side searches for user specified strings and patterns. To access this new
search feature, right-click on the Schemas workspace > Search Table
Data.
 Schema Inspector: allows you to browse general information from
schema objects. It is also possible to maintain tasks such as ANALYSE,

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 42 of 95


OPTIMIZE, CHECK and CKECKSUM TABLE for tables. Right-click a schema
and select the Schema Inspector to access this feature.
 Cascaded DELETE statements generator: a series of statements needed
to delete a row from a table can be generated including rows from other
tables that reference the table. The SELECT version allows you to preview a
row to be deleted. Right-click a table and select Copy to Clipboard
>Delete with References.
 Improved Server Status information: Additional server status
information has been added, and the user interface is improved. Select
Server Status from the Management pane tab to open this feature.
 Performance: this new section feature includes Dashboard, Performance
Reports and Performance Schema Setup pages. Generally, the performance
reporting feature provides graphical representation of key statistics from
the MySQL server status.
 Additional Client Connection Information: this feature is accessible by
clicking the Server tab >Client Connections.

MySQL Workbench has improved in both look and functionally. Once you
become familiar with the new version you will appreciate its efficiency.

2.1.2 Introduction to security


MySQL server supplies a flexible privilege system implemented by the grant
tables in the mysql database. Tables can be set to permit or deny database
access to clients. This provides security against unauthorised network access
to the data.

MySQL security is based on Access Control Lists (ACLs) for all connections,
queries and other operations that users can attempt to perform. There is also a
support for SSL-encrypt connections between MySQL clients and servers.
MySQL stores passwords in the mysql.user table. Access to this table should
be granted to administrative accounts only. MySQL 5.6 introduces password-
expiration capability, which enables administrators to expire account
passwords and require users to reset their passwords. The following statement
is used to expire an account password:
ALTER USER 'cti'@'localhost' PASSWORD EXPIRE;

This statement modifies the row of the mysql.user table associated with cti2
account, setting the password_expired column to ‘y’.

The same feature can be performed using the MySQL workbench 6.3 as shown
in Figure 2.1 – account password expire. To access user accounts in
MySQL workbench, click Users and Privileges on the navigator pane on the
left hand side. Note that an admin password will be required for you to access
user accounts.

If the client is disconnected from the server, the server will return an
ER_MUST_CHANGE_PASSWORD_LOGIN error.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 43 of 95


Shell:>mysql -u ctiMLM_stu -p

Enter password: *************

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 82

Server version: 5.7.13-log

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserve

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statem

mysql> show databases;

ERROR 1820 (HY000): You must reset your password using ALTER USER statement.

Figure 2.1 – Account password expire

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 44 of 95


2.1.3 Introduction to internal security
Internal security refers to the files within the databases and how to prevent
unauthorised filesystem access on the server.

2.1.3.1 How database content is attacked


During the installation of MySQL, certain log files are created to store various
forms of information. These log files need to be kept secure as anyone with log
file access can monitor the changes made to the contents of the database; this
includes any passwords stored in the database content.

An attacker who has log file read access may use a command such as grep (in
Unix or Linux) on the log file to look for keywords such as GRANT or
PASSWORD to gain access to your password.

Ideally when setting up your database, you want to allow access to the file, but
not full control over it.

For the purpose of this module we will not go into detail about internal
security, because we are operating MySQL on the Windows environment and
already have full control over the computer and there are no other local users.

2.1.4 External security


External security refers to issues which pertain to unauthorised network
access. The MySQL security system allows you to set up user access privileges
in various ways, e.g. issuing statements using CREATE USER, GRANT, and
REVOKE. All these statements modify the grant tables which control client
access.

2.1.4.1 MySQL grant tables


The grant tables are initialised when MySQL is installed for the first time. Any
access to MySQL databases, attempted by clients who have connected to the
server over the network, is controlled by the contents of the grant tables.
These grant tables are stored in the mysql database.

Three types of privileges are used by the grant tables:

 Administrative privileges
 Database privileges
 Table privileges

In order for administrative privileges to be set, a MySQL user account consists


of a username and the name of the client host from which the user must
connect to the server. The account name is specified in SQL statements by

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 45 of 95


means of ‘user_name’@’host_name’ format. Your MySQL account needs the
grant privilege to have access to user management features.

You can easily create, remove, or rename user accounts with the following
statements:

 CREATE USER

The following example creates a user named ctiMLM_stu, who can only
connect from the localhost pc. The account password is specified by the
IDENTIFIED BY clause.

CREATE USER ‘ctiMLM_stu’@’localhost’ IDENTIFIED BY ‘CTIPassword45’;

Once you have created the USER privileges, issue the following statement to
check the user you just created:

SELECT host, user, HEX(authentication_string) FROM mysql.user WHERE user LIKE


‘%ctiMLM_stu%’;

Figure 2.2 – CREATE USER and QUERY CREDENTIALS

 DROP USER

The following example shows how to drop a user account:

DROP USER 'ctiMLM_stu'@'localhost';

 RENAME USER

It is also possible to rename a user as follows:

RENAME USER 'ctiMLM_stu'@'localhost' TO 'cti1'@'localhost';

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 46 of 95


Granting privileges
Privileges can be granted to user accounts in the following way:

GRANT SELECT, INSERT, UPDATE, DELETE ON ctiMLM_stu.* TO 'cti2'@'localhost'


IDENTIFIED BY 'CTIPassword45';

The SELECT, INSERT, UPDATE, and DELETE privileges on any ctiMLM_stu


database table are assigned to the user called cti2 who can only connect from
the localhost machine with the password of mysql002. The localhost machine
in this context is the machine that the MySQL Server is running on. Now the
cti2 user can read and modify the contents of existing tables but cannot create
tables.

The GRANT statement will alter the user account if it already exists, or
alternatively create the user account if it does not exist.
Viewing privileges
The following statement displays account privilege information:

SHOW GRANTS FOR 'cti2'@'localhost';

Revoking privileges
The following REVOKE statement can be used to revoke specified privileges
from a user account:

REVOKE UPDATE, DELETE ON ctiMLM_stu.* FROM 'cti2'@'localhost';

Previously we granted SELECT, INSERT, UPDATE, and DELETE privileges to this


user account. Note that this statement only removes the UPDATE and DELETE
privileges from the account.

2.1.5 Creating a connection profile


A connection profile is the profile of a user in MySQL and the MySQL
workbench working directory. The profile ensures that only an authorised user
can log in to MySQL server; by default there is a system profile that is set up
when the user installs the MySQL server. The system Profile tab allows you to
specify host-specify information. This is done mainly through selecting System
Type with its corresponding Installation Type. Here you have the flexibility of
choosing the hosting that you want to use when accessing your MySQL server.

 When you first open the MySQL Workbench, a home screen will be shown.
 The MyFirstConnection connection example has already been created in this
case. Follow the steps below to create your server connection profile.
 From the MySQL Workbench Home Window, click the [+] icon next to the
MySQL Connections label. This will open a New Connection Setup wizard

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 47 of 95


as shown in Figure 2.5 below. On the connection name enter
MyFirstConnection.
 In Figure 2.5, default connection values are for a typical local setup; click
the Test Connection button to check the connectionparameters. Do not
press OK.

Click Configure Server Management, which will open the Configure Local
Management wizard.

Figure 2.4 – MySQL Workbench home

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 48 of 95


Figure 2.5 – Connect to Database

 On the Configure Local Management wizard, read the introduction and click
Next.
 The connection will now be tested as shown in Figure 2.6, and Database
connection tested successfully should be displayed. If it is not, click Back to
check which information you entered wrongly. You can toggle the Show
Logs to view additional details about the tested connection.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 49 of 95


Figure 2.6 – Test Database connection

 Now click Next, and select the appropriate MySQL service for the MySQL
connection as shown in Figure 2.7.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 50 of 95


Figure 2.7 – Windows configuration parameters

 Click Next, and the Testing host machine wizard should appear. Click Next
on this wizard and choose I’d like to review the settings again.
 Now a Review Remote Management Settings wizard appears. Check the
Change Parameters box if you want to check or edit information about
the MySQL configuration file.
 The MySQL Config File should appear. Click Check path to ensure the
correct path is used and then click NEXT.
 The next wizard provides optimal space to enter your own commands for
starting, stopping and checking the MySQL connection. Default values are
used to this, so leave these options blank and click FINISH.
 The original Set New Connection wizard should appear here. Click Test
connection and then click OK.

Note If you encounter any issues or errors during the MySQL Workbench
profile connection setup, you can watch this video from MySQL:
http://www.youtube.com/watch?v=DCgRF4KOYIY

 Now connect to your created connection profile.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 51 of 95


 In the Password textbox, enter the password that you have used to create
the root account.

2.1.5.1 Using the GUI to set privileges


MySQL Workbench provides an easy way to work on a Graphical User Interface
(GUI). Now that we have created our connection successfully, let us set some
user privileges.

 On the home screen double-click the connection we have just created and
enter the password to connect.
 Once connected, go to the Navigator pane on the left, under the
Management pane tab, and click Users and Privileges.
 Enter the password if requested, and you should see the wizard below:

Figure 2.8 – Users and Privileges


Note the two panels on the wizard. Under User Accounts you can create or
delete an account as we did with the MySQL command above. The second
panel shows details for a selected account.

Now, if you select the root user account and select Administrative Roles, you
will notice that all the roles are checked. But the users cti_student and cti2
are not assigned to any role. The third panel displays the privileges which the
user will be entitled to when assigned a certain role. See Figure 2 .9  User
Roles and Privileges.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 52 of 95


You can create your account users with their roles and assign relevant
privileges. We have discussed the login panel, where you can set user
passwords to expire for security reasons. On the account limit, you can limit
the user connection time and the number of queries that can be executed.

Figure 2.9 – User Roles and Privileges

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 53 of 95


2.1.5 Key terms
 Grant
 Revoke
 External Security
 Privileges

2.1.6 Exercises

 Ensure you have created a profile connection.


 Create user accounts and ensure the correct
privileges are set for all accounts.
 Expire the password of a certain user and test it
later.

2.1.7 Revision questions

1. True/False? Internal security refers to issues


which pertain to unauthorised network access.

2. Which statement can be used by an attacker on a


log file to look for keywords such as GRANT or
PASSWORD?
A. grep
B. seek
C. grant
D. All of these

3. Name the three types of privileges used by the


grant tables.

4. What happens when the following statement is


executed?

SELECT host, user, password FROM mysql.user WHERE


user LIKE '%cti%';

5. The ___ statement will alter the user account if it


already exists, or alternatively create the user
account if it does not exist.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 54 of 95


2.2 Avoiding access control risks

At the end of this subsection you will be able to:

 Control users.
 Find non-authentication accounts.
 Change passwords or reset lost passwords.

It is advisable to avoid creating an account with an empty username


(anonymous user). Even a user with no privileges can cause damage and may
gather information about databases and tables. The user can monitor the
server with SHOW STATUS and SHOW VARIABLES.

2.2.1 Finding non-authenticated accounts


Accounts with no authentication required must be either removed or assigned
require authentication. To find the accounts with no password or no use of
authentication plugin, use the following query:

SELECT Host, User FROM mysql.user


WHERE Password = ‘’ AND plugin = ‘’;

To remove such accounts, use the DROP USER statement. To require


authentication, you can assign a password:

SET PASSWORD FOR account = PASSWORD(‘password’);

The passwords must be in the new secure hash format. The old format has
values with length of 16 and do not begin with ‘*’ character. Accounts that are
using this older format can be identified by using this query:

SELECT Host, User FROM mysql.user WHERE LENGTH(Password) =16;


SELECT Host, User FROM mysql.user WHERE Password NOT LIKE ‘*%’;

If any accounts are identified by these statements:

 If the old_passwords system variable is set to 1 (ON), restart the server


without enabling it.
 For subsequent server restart, always enable the secure_auth system
variable. This prevents a client from resetting its password to the old format
with OLD_Password() and connecting using that password. As from MySQL
5.6.5 secure_auth is enabled by default.
 Use SET PASSWORD to reset the password for each account that has an old
format password.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 55 of 95


 By setting global sql_mode value to include the NO_AUTO_CREATE_USER
mode you will prevent GRANT statements from creating insecure new
accounts.

Be careful with the GRANT OPTION privilege. Two clients with distinctive
privileges that both have the GRANT OPTION privilege can make each other’s
rights more powerful. Do not lightly grant the FILE privilege, which is especially
dangerous.

2.2.1.1 Changing passwords or resetting lost passwords


It is always secure to have a password on your server for several reasons like
data loss and data misuse by unauthorised users (intruders). Forgetting a
password can be stressful because no access will be granted to the server until
you get your password right.

One way to change or reset an account’s password is to use an UPDATE


statement that identifies the User and Host for the account’s user table row,
then flush the privileges:

->USE mysql;
->UPDATE user SET Password=PASSWORD('myNewPassword')
->WHERE User ='mandla' AND Host= 'localhost';
-> FLUSH PRIVILEGES;

However, it is easier to use SET PASSWORD because you name the account using
the same format like other account management statements, and it is
unnecessary to flush privileges explicitly:

->SET PASSWORD FOR 'mandla'@'localhost' = PASSWORD('myNewPassword');


SET PASSWORD allows you to change a user’s password. To change the
password of another account, you must have the UPDATE privileges for the
MySQL database.

If you need to reset the root password because you have forgotten it and you
cannot connect to the server, then you have a problem because normally you
must be connecting as root to change the root password.

To reset the root password for MySQL on Windows, follow the following steps:

 While logged on to your system as Administrator, stop the MySQL server if


it is running.
 Go to Services manager. From the Start menu, select Control Panel >
Administrative Tools > Services. Find MySQL service in the list and stop
it.
 Create a text file containing the following statements. Replace the
password with the password that you want to use:

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 56 of 95


UPDATE mysql.user SET Password=PASSWORD('MyNewPass')
WHERE User ='root';
FLUSH PRIVILEGES;

The UPDATE statement resets the password for all root accounts, and the
FLUSH statement tells the server to reload the grant tables into memory so
that it notices the changes made.

 Save the file. In this example the file is named C:\mysql-init.txt.


 Open a console window to get the command prompt: From the Start menu,
select Run under Accessories, and enter cmd as the command to be run.
 Start the MySQL server with the special --init-file option (notice the
backslash on value option is doubled.):

C:\> C:\mysql\bin\mysqld --init-file=C:\\mysql-init.txt

 Adjust the command according to a location of your MySQL installation.


 The server will execute the contents of the file named by the –init-file
option at start-up, changing each root account password.
 You may add the –console option to the command if you want server
output to appear in the console window.
 For MySQL installed using MySQL installation Wizard (which is usually the
case), specify a –defaults-file option:

C:\> "C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqld.exe"


--defaults-file="C:\\Program Files\\MySQL\\MySQL Server 5.6\\my.ini"
--init-file=C:\\mysql-init.txt

The appropriate –defaults-file setting can be found using the Services


Manager. From the Start menu, select Control panel > Administrative
Tools> Services. Find the MySQL service in the list, right-click it, and choose
Properties.

 Once the server has started successfully, delete C:\mysql-init.txt


 Stop the MySQL server, then restart it in normal mode.

Now you should be able to connect to MySQL server as a root with a new
password.
Note Resetting the root password will not be tested in the examination, but
it is good to know how to in case you come across a situation that
requires this process.

You may refer to MySQL website if you encounter any errors:


http://dev.mysql.com/doc/mysql-windows-excerpt/5.5/en/resetting-
permissions-windows.html

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 57 of 95


2.2.2 Specifying account names
The account name in the account management statement consists of username
and hostname. For example: CREATE USER ‘cti’ @’localhost’. In MySQL, we
specify not only who can connect but from where they can connect. This allows
us to set up separate accounts for two users who have the same name but
connect from different locations. MySQL gives us the ability to distinguish
these accounts and assign privileges to each one independently. The server
stores username and hostname values in the User and Host columns of the
user table row for each account, and any other grant table rows associated
with the account. The account name that is in current use at a session can be
specified as CURRENT_USER() or CURRENT_USER. Choosing an account value
appropriately will allow the user to connect from a specific or broad set of
hosts as specified by the administrator. Access can be limited to a single host if
it is known that a user will only connect from that host:

CREATE USER 'james'@'localhost' IDENTIFIED BY 'mypassword';


CREATE USER 'fred'@'ado.mine.net' IDENTIFIED BY 'thispassword'

The strictest form of access is to allow the user to connect on one host. In a
case where you have a user who travels a lot, this user will require a
connection from hosts all over the world. If the user’s name is tom, you can
allow him to connect from anywhere like this:
CREATE USER 'tom'@'%' IDENTIFIED BY 'thispassword';

The % character works as a wildcard with the same meaning as in LIKE


pattern match. Therefore, it specifies hostname; % means “any host”. This is
the easiest way to set up a user but it is also the least secure.

Note The hostname is the host from which the client will be connecting. It
is not the server host to which the client will connect (unless they
happen to be the same).

Using % may also result in occasional confusion for the administrator,


because:

 The user tom can connect remotely from any host.


 If tom tries to connect locally from the server host, the attempts fails.
 This problem is caused by anonymous user rows that have blanks in the
User table.
 These rows are created by the mysql_install_db initialisation script under
Unix and are presented in the pre-initialised User table included with the
Windows distribution.

There are two solutions to this problem: one is to set up a second account for
tom that explicitly lists localhost as the host value:

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 58 of 95


Figure 2.10 – Multiple host user sorting

GRANT ALL ON sampdb. * TO 'tom'@'localhost' IDENTIFIED BY 'thispassword';

The above statement commands the server to sort the user table rows as
shown in Figure 2.10
Now tom can connect from the local host, because the row with localhost and
tom matches ahead of the anonymous user rows. The disadvantage of having
two accounts is that whenever data about tom needs to be changed, changes
must be made twice.

The second solution is to remove the anonymous accounts from the user table,
which is a much easier solution:

DROP USER ''@'localhost';


DROP USER ''@'muller.example.com'

Now tom can connect from the local host with success because there are no
rows in the user table that match before his row. To make MySQL
administration easier, it is recommended that you delete anonymous accounts
from grant tables.

2.2.3 Key terms


 Anonymous user
 Authentication

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 59 of 95


2.2.4 Exercises
Find all accounts with no password or no use of authentication
plugin, and use the following query to remove them:

DELETE FROM mysql.user WHERE user= '' or password='';


FLUSH PRIVILEGES;

2.2.5 Revision questions

1. True/False? Accounts with empty username are


considered to be good practice in MySQL.

2. True/False? Anonymous accounts are created in order to


protect data from being stolen.

3. What are functions of the following two statements?

SELECT Host, User FROM mysql.user WHERE


LENGTH(Password) =16;

SELECT Host, User FROM mysql.user WHERE Password NOT


LIKE '*%';

4. True/False? The following statement is used to change the


password of another account:

->SET PASSWORD FOR 'mandla'@'localhost' =


PASSWORD('myNewPassword');

5. The account name in a current session can be specified as


_________.

6. Describe the best solution to the problem of a frequently


travelling user.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 60 of 95


2.3 Setting up secure connections

At the end of this subsection you will be able to:

 Set up a secure connection over SSL.

2.3.1 Introduction to secure connections


MySQL supports secure connections between MySQL clients and the server
using the Secure Socket Layer (SSL) protocol. This means that an
administrator with access to the network will watch all traffic and look at the
data being sent or received.

Secure connections are mainly used when information is transmitted over a


network that may be susceptible to snooping. These secure, encrypted
connections are created over SSL. SSL uses a different encryption algorithm to
ensure that data received over a public network can be trusted.

Advantage of SSL:

 Information transmitted over a network is more secure.

Disadvantage of SSL:

 Slower performance due to additional computational burden.

Should you need a higher performance connection, you should take a risk and
use an unencrypted connection.

2.3.2 Secure connection setup


The following steps will show you how to set up a secure connection:

 First you need to check if the server supports SSL; to do this, issue the
following statement after the server is started:

mysql> SHOW VARIABLES LIKE 'have_ssl';

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 61 of 95


Figure 2.10 – Displays SSL support statement

 Under the value column, you will see DISABLED; this means that SSL
support is not available.

Three main files are used to enable SSL and set up secure communications
between the server and its clients.

 A Certificate Authority (CA) certificate –This is a trusted third party


which is used to verify the authenticity of the client and server certificates.
 A certificate file – This authenticates one side of the connection to the
other.
 A key file – This is used to encrypt and decrypt traffic over the connection.

The server’s certificate and key files must be installed first. These files can be
obtained from the sampdb file in the resource folder under the ssl directory.
The following files can be used:

 ca-cert.pem – Certificate Authority certificate


 server-cert.pem – Server’s certificate
 server-key.pem – Server’s public key

Copy the files into the server’s data directory and add the lines to the [mysqld]
group in the option file which is read by the server at start up. The option must
indicate the path names to the certificate and key files. Once the SSL files have
been installed and the option files have been modified, restart the server and
issue the have_ssl statement. The value column should contain Yes, which
indicates that the server has been enabled to allow encrypted connections.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 62 of 95


NOTE Setting up a secure connection will not be tested in the examination,
but it is important to know how to set one up.

For your own interest, read more about this on mysql website:

http://dev.mysql.com/doc/refman/5.7/en/secure-connections.html
http://thecpaneladmin.com/installing-ssl-certificate-mysql/

2.3.3 Key terms


 SSL
 Certificates

2.3.4 Exercises

Make sure your secure connection has been set up correctly.

2.3.5 Revision questions

1. What does SSL stand for?

2. What is the function of the following command?

mysql> SHOW VARIABLES LIKE 'have_ssl';

3. What is the difference between encrypted and unencrypted


connection types?

4. True/False? The value DISABLED means that the server


cannot have SSL support.

5. Which one of the following is a file which can be used as a


server’s certificate and key file?
A. ca-cert.pem
B. sa-cert pem
C. server-ca-cert.pem
D. ca-key.pem

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 63 of 95


2.3.6 Suggested reading

DuBois, Paul. 2013. MySQL. Fifth Edition. Pearson Education.


Chapter 13.

https://dev.mysql.com/doc/workbench/en/wb-what-is-new-
63.html

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 64 of 95


2.4 Test your knowledge

NOTE The following questions must be completed and handed in to your


lecturer to be marked.

2.4.1 Exercises
Change the password of a user in your database. Test the new password and
ensure it works correctly.

2.4.2 Revision questions

1. Log files need to be kept secure as anyone with ___ can monitor the
changes made to the contents of the database.

2. True/False? Password privileges are one of the privileges used by the


grant tables.

3. What would you use to specify an account password?

4. True/False? It is not possible to rename a user.

5. True/False? Secure connections are mainly used when information is


transmitted over a network that may be susceptible to snooping.

6. What is an advantage of using SSL?

7. What are the three main files used to set up an SSL connection?

8. True/False? It is not possible to reset the root password in MySQL.

9. True/False? MySQL allows an anonymous account for data protection


reasons.

10. True/False? An anonymous user is harmless to the database.

11. True/False? In MySQL, changing a forgotten root account password is


more complicated than changing any other account password.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 65 of 95


Unit 3 – Maintaining a Database

The following topics will be covered in this unit:

 Database maintenance
 Database backup

NOTE In the examination, application questions will be asked where


students will need to be able to apply their knowledge of the
concepts covered in this unit.

Read through the following tutorial:

DuBois, Paul. 2013. MySQL. Fifth Edition. Pearson


Education. Chapter 14.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 66 of 95


3.1 Database maintenance

At the end of this subsection you will be able to:


 Perform database maintenance.
 Manage locking.
 Use server auto-recovery capabilities.

3.1.1 Introduction to database maintenance


Database maintenance is performed to ensure that MySQL always runs
smoothly. However, there are some problems which may occur that can result
in damage to database tables: power outages; hardware failure; improper
shutdown of the MySQL server.

The following steps can be used as a guideline to ensure that one is prepared
for database problems:

 Enable the auto-recovery options.


 Set up scheduled preventative maintenance to perform table checking
periodically.
 Set up a database backup schedule.

Should table damage or data loss occur, use one of the following steps:

 Check the tables, and fix any tables which are found to be corrupt.
 Perform data recovery using your backups and binary log.

Various tools are available to help:

 Transactional storage engines which can perform auto-recovery.


 MyISAM automatic table repair can be enabled.

Programs such as mysqldump and mysqlhotcopy are used to create backups.


The server can perform table maintenance on demand by using:

 CHECK TABLE
 REPAIR TABLE
 mysqlcheck program

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 67 of 95


3.1.2 Performing database maintenance
When maintenance operations are performed, the program doing the reading
can become confused if the table is changed by another program at the same
time. To prevent this from occurring, the server has two locking methods:

Internal locking – used to keep requests from being interrupted by another


client. This locking method may also be used to prevent a table from being
accessed while you are working with the table externally to the server.
External locking – used to prevent other programs from modifying table files
while it is using them.

3.1.2.1 Locking tables for read-only access


This protocol is used when only the table’s files need to be read, e.g. creating
copies of the files or checking the tables for inconsistencies.

%mysql db_name
mysql> LOCK TABLE tbl_name READ;
mysql> FLUSH TABLE tbl_name;

Remember to always release the lock once you have completed working with
the table.

mysql> UNLOCK TABLE;

3.1.2.2 Locking tables for read/write access


This protocol is used for operations such as table repair that need to modify a
table’s files.

%mysql db_name
mysql> LOCK TABLE tbl_name WRITE;
mysql> FLUSH TABLE tbl_name;

When using the read/write protocol, a second FLUSH must be performed


before the lock can be released.

mysql> FLUSH TABLE;


mysql> UNLOCK TABLE;

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 68 of 95


3.1.2.3 Locking all databases for read-only access
To prevent clients from making any changes to tables, you can place a read
lock on all the tables in the database.

mysql> FLUSH TABLE WITH READ LOCK;


mysql> SET GLOBAL read_only = ON;

When using the lock on all database protocols, the FLUSH statements need a
global read lock and an SET statement, which blocks activity until the other
clients release the table locks they have and complete the outstanding
transactions on the tables.

To allow changes to be made, issue the following commands:

mysql> SET GLOBAL read_only = OFF;


mysql> UNLOCK TABLES;

NOTE Using a database locking protocol only allows clients to read from the
tables. Therefore, clients cannot make any update changes and for
this reason, you should not hold the server lock longer than
necessary.

3.1.3 The Server’s auto-recovery capabilities


The MySQL server’s crash recovery capability is the first defence mechanism in
maintaining database integrity. This includes:

 Transactional storage engine recovery which happens at server start-up


automatically.
 MyISAM: is optional and must be enabled expressly.

MySQL is designed to recover from various problems. If you do nothing more


than restart the server normally, it will make necessary corrections for you in
many cases. For instance, the InnoDB storage engine checks for problems
automatically. Committed transactions in its redo log but not yet flushed to
tables are rolled forward. Uncommitted transactions at the time of crash are
rolled back (discarded) using the undo log. The InnoDB tables are left in a
consistent state, and their contents will reflect all transactions that had been
committed before the crash.

It will be helpful to explicitly enable the MyISAM option. To enable MyISAM


table recovery, start the server with the myisam_recover_options system
variable set. The variable is a comma-separated list of one or more of the
following options:

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 69 of 95


 BACKUP: create a backup of the table if the repair will change it.
 FORCE: force recovery even if more than a row of data will be lost.
 QUICK: quick recovery.
 DEFAULT: recover with no special handling.
 OFF: no recover.

Enabling MyISAM auto-recovery is a useful general maintenance strategy.

3.1.4 Key terms


 Auto-recovery
 Preventative maintenance
 Internal locking
 External locking
 FLUSH
 UNLOCK

3.1.5 Exercises

1. Write a myisamchk command to perform a table


repair and attempt to fix indexes only.

2. Write a myisamchk command to perform a table


repair and attempt to fix indexes and data files.

3. What is the SQL command for repairing a table?

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 70 of 95


3.1.6 Revision questions

1. True/False? Power outages cannot cause damage


to databases.

2. What steps can be used as guidelines to ensure


you are prepared for database problems?

3. Which of the following does the server use to


perform on-demand table maintenance?
A. CHECK TABLE
B. REPAIR TABLE
C. mysqlcheck program
D. mysqldump program
E. myisamchk program

4. What is the difference between internal locking and


external locking?

5. What is the following statement used for?

mysql> FLUSH TABLE WITH READ LOCK;

mysql> SET GLOBAL read_only = ON;

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 71 of 95


3.2 Database backups

At the end of this subsection you will be able to:

 Perform database backups.

Database backup and restore tasks can be performed by using either the
command prompt or terminal programs or, in a graphical context, using
MySQL administrator.

3.2.1 Backup
The mysqldump program can be used in the following way to back up a
database:

mysqldump [options] db_name [tables] >file_name.sql

If you do not name any tables following db_name or if you use


the - -databases or --all-databases option, entire databases are dumped. To
get a list of the options your version of mysqldump supports, execute
mysqldump –help on the command line.

3.2.1.1 Back up a single database


The example below demonstrates the process of backing up a single database.
Here we use the cd_collection database to facilitate the process.

%mysqldump –u root –p[root_password]cd_collection>cd_collection.sql


% mysqldump –u root –p[root_password] [database_name] >dumpfilename.sql

The cd_collection will contain drop table, create table and insert commands for
all tables in the cd_collection database.

The mysqldump client is used to dump databases or collection of databases for


backup or transfer to another SQL server. A dump file is a snapshot showing
modules loaded and files executed when a dump was taken.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 72 of 95


3.2.1.2 Backup multiple databases
The first thing to do before backing-up multiple databases is to identify the
databases, using the show databases command as shown below:

% mysql –u root – p [root_password]


mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| cd_collection |
| cti |
| mysql |
| performance_schema |
| sakila |
| sampdb |
| test |
| world |
+--------------------+
10 rows in set (0.00 sec)

If we want to back up both cd_collection and cti, we execute the mysqldump


as follows:

# mysqldump –u root –p [root_password] –databases


cd_collectioncti>cd_collection_cti.sql

To back up all databases, execute the following statement:

% mysql –u root –p [root_password] –all databases> /tmp/all-database.sql

The following table summarises the most common options to use with
mysqldump:

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 73 of 95


Table 3.0 – mysqldump options

Option Description

Interprets any non-option argument as a database


--databases or –B name and dumps all the tables in each of the
databases to the specified script file.

This option dumps all the databases on the server to


--all-databases or –A
the specified script file.

Precedes the dump output of each table with the


--add-drop-table
appropriate DROP TABLE statement.

Encloses INSERT statements with appropriate table


--add-locks
locks for each of the dumped tables.

Produces CREATE TABLE statements that include all


--create-options the MySQL-specific options with which each table
was created initially.

Includes ALTER TABLE statements in the dump file


--disable-keys that disable and enable index updating. Makes
reloading faster for MyISAM tables.

By default mysqldump writes each row as a separate


INSERT statement. This option produces multiple-
row INSERT statements that add several rows to the
--extended-insert or –e table at a time. Multiple row statements can be
reloaded more efficiently, although they are less
readable and less portable than single-row
statements.

Instructs the server to flush the logs before starting


the dump. This causes the next binary log to be
--flush-logs synchronised to the time of the dump, which will
simplify data recovery operations should it become
necessary.

Acquires a READ LOCAL lock for the tables before


--lock-tables
starting the dump.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 74 of 95


This option causes CREATE DATABASE statements to
--no-create-db or –n
be left out of the script file.

This option leaves out the CREATE TABLE statement


--no-create-info or –t for situations when you only want the table’s data to
be written to an SQL script file.

This option leaves out the INSERT statements that


--no-data or –d contain the table data. Use this option if you are only
interested in dumping empty table structures.

Turns on an additional set of options to make the


dump and reload operations more efficient. The
statement is the equivalent to using:

–-add-drop-table, --add-locks, --create-options,


--opt --quick, --extended-insert, --lock-tables, and

–-disable-keys options together. This option is also


enabled by default. To disable it, use –-skip-opt. You
can also disable the sub-options individually, e.g. –-
skip-quick.

This option causes mysqldump to write the dump


output as it reads each row from the server, where it
--quick
usually reads all the rows from a table into memory
before writing the output.

Dumps tables within a transaction. This is necessary


--single-transaction
when dumping InnoDB tables.

Let’s practise backing up our entire CTI database to a


backup script file.

 From the command prompt or terminal, run the following command:

mysqldump –u root -pcti> c:\cti_backup.sql

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 75 of 95


 You will be prompted for the MySQL root user’s password. Alternatively, you
can also configure the mysqldump connection parameters in the my.cnf
options file.

3.2.2 Restore
To restore a database you can use mysql monitor in the following way:

mysql db_name<file_name.sql

Try restoring the CTI database again from the previously-


created backup script.

 From the command prompt or terminal, run the following command:

mysql cti< c:\cti_backup.sql

 Use the MySQL console to confirm that the cti database has been restored.

3.2.3 Using MySQL Workbench Backup


Firstly, we need to create a backup project. The advantage is that the backup
project can be saved and scheduled for automatic execution at specific times.
MySQL Workbench is a visual tool for administering a MySQL database as we
have previous seen it. MySQL Workbench replaces previous MySQL GUI tools
such as MySQL Administrator and MySQL Query Browser, giving the
administrator an easy way to configure, maintain, and back up a database in
one place. MySQL Workbench can export a backup of your database to a file on
your local computer; this is commonly referred to as a data dump.
The following are the database backup steps used in MySQL Workbench:

 Open MySQL Workbench and connect to your server instance.


 Click Manage Import/Export under Server Administration on the right of
the Workbench window. If you cannot see this option, make sure the Home
tab is selected.
 Select the database to back up and click OK.
 If prompted, enter your database password.
 Select the Export to Disk tab.
 In the Select Database Objects to Export section, select your database by
checking the relevant box in the Export column.
 Select the tables you wish to export. Click Select All Tables if you would
like to export the contents of your entire database.
 Choose where you would like to save your database backup. There are two
options available:

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 76 of 95


 Export to Dump Project Folder: MySQL Workbench will create a separate
backup file for each table in your database, which will make it possible to
store selected tables in the future without the need to restore the entire
database.
 Export to Self-Contained File: All selected tables will be exported to one
single SQL file.

 Choose the first option and ensure the correct location to save your backup
is selected.
 Click Start Export and enter the database password if prompted.

Now and then we will need to restore the backed up database in order to use
it.

Restore
To restore a database using MySQL Work workbench, we follow similar steps
as we have made a backup.

 Click Manage Import/Export under Server Administration on the right of


the Workbench window. If you cannot see this option, make sure the Home
tab is selected.
 Select your database and click OK.
 Enter your database password if prompted.
 Select the Import from Disk tab.
 Since we created our backup using the Export to Dump Project Folder, here
we do a similar task.
 Select Import from Dump Project Folder and enter the location in the Folder
Path text field. Click Load Folder Contents.
 Select the tables you would like to restore from a backup.
 Click Start Import and enter the database password if prompted. This
process may take several minutes depending on the size of your database
backup.
 Now select the previously-created backup file.

You can now choose to restore it to a different database schema if needed. In


the Restore Content tab, you can also analyse the backup file’s content to
select the members to restore if you only want to restore a previous version of
a trigger or routine, for instance. Lastly, to initiate the restoration process,
simply click Start Restore.

3.2.4 Key terms


 Backup
 Restore

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 77 of 95


3.2.5 Exercises
1. Create a backup of your database using each of the
methods in this unit. Restore the database for each
backup.

3.2.6 Revision questions

1. What occurs if you do not name any tables


following db_name?

2. True/False? To restore a database by using MySQL


Administrator, click on the restore section.

3. What does the following command do?

mysqldump --help

4. _______ instructs the server to flush the logs


before starting the dump.
A. –flush –logs
B. –lock –tables
C. –opt
D. –quick

5. –disable –keys includes _____ statements in the


dump file that disable and enable index updating.

6. True/False? The following SQL statement will make


a backup of a database named cd_collection.

mysqldump –u root –
p[root_password]cd_collection>cd_collection.sql

7. True/False? mysqldump is used to dump a database


or a collection of databases for backup or transfer
to another SQL server.

3.2.7 Suggested reading

DuBois, Paul. 2013. MySQL. Fifth Edition. Pearson


Education. Chapter 14.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 78 of 95


3.3 Test your knowledge

NOTE
The following questions must be completed and handed in to your
lecturer to be marked.

3.3.1 Exercises
1. To back up your database, it is necessary to:

A. take down the server


B. lock and flush the tables
C. both A and B
D. none of the above

2. You should lock tables manually before executing:

A. a manual backup
B. mysqldump
C. mysqlhotcopy
D. none of the above

3. Which table types can you check with CHECK TABLE?

A. InnoDb and MyISAM


B. MyISAM only
C. MyISAM and BDB
D. InnoDB and BDB

4. Which table types can you repair with REPAIR TABLE?

A. InnoDb and MyISAM


B. MyISAM only
C. MyISAM and BDB
D. InnoDB and BDB

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 79 of 95


3.3.2 Revision questions

1. True/False? External locking is used to keep requests from being


interrupted by another client.

2. True/False? This protocol is used when the table’s files do not need to be
read.

%mysql db_name

mysql> LOCK TABLE tbl_name READ;

mysql> FLUSH TABLE tbl_name;

3. When using the read/write protocol, a second ____ must be performed


before the lock can be released.

4. True/False? Using the ALL DATABASE LOCKING protocol only allows clients
to read from the tables.

5. Match the following:

A. Interprets any non-option argument as a --add-drop-table


database name and dumps all the tables in
each of the databases to the specified script
file.

B. Precedes the dump output of each table with --databases or –B


the appropriate DROP TABLE statement.

C. Acquires a READ LOCAL lock for the tables --no-create-db or –n


before starting the dump.

D. Causes CREATE DATABASE statements to be --lock-tables


left out of the script file.

E. --single-transaction

F. --add-locks

G. --no-create-info or –t

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 80 of 95


Glossary

Term Description

A set of properties (name, data type, size, etc.) used to


Attributes
characterise the data items of entities.

The process of copying all table data and metadata from


Backup
a MySQL instance, for safekeeping.

A file containing a record of all statements that attempt


Binary log
to change table data.

A certain language element as part of a statement. For


Clause
example: the WHERE clause defines search criteria.

The InnoDB term for a primary key index. InnoDB table


storage is organised based on the values of the primary
Clustered index
key columns, to speed up queries and sorts involving
primary key columns.

An SQL statement that ends a transaction, making


COMMIT
permanent any changes made by the transaction.

A set of values of a single table which resides in the


Column
same position within its rows.

Similar to attributes, constraints define rules at a higher


level, which data items must conform to. For example:
Constraint
nullability, primary and foreign key, uniqueness, default
value, user-defined-criteria like STATUS < 10.

A set of tables. Those tables contain user data and


Database
the Data Dictionary.

Entity An identifiable object like an employee or a department.

Entity-type A group of attributes describing the structure of entities.

A value used to reference a primary key. Its value will


Foreign key
match a primary key value outside own table.

An index is a construct containing copies of original


Index values and back references to their original rows. Its
purpose is the provision of fast access to the original
data. To achieve this, an index contains some kind of

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 81 of 95


collocation.

The system of protecting a transaction from seeing or


Locking changing data that is being queried or changed by other
transactions.

A backup that reproduces table structure and data,


Logical backup
without copying the actual data files.

NULL is a special value that is used to indicate the


absence of any data value. For example, it makes a
NULL difference whether a temperature is measured and
stored as 0 degrees or whether the temperature is not
measured and hence not stored

A language element of the WHERE clause which specifies


Predicate conditions that evaluate to the SQL three-valued logic
(true/false/unknown). Predicates are used to find rows.

A value or a set of values used to identify a single row


Primary key
uniquely.

An often-used statement which retrieves data from the


Query database. It is introduced by the keyword SELECT and
usually contains a predicate.

A reference between two different or identical entities.


Relationship
References are not implemented as links.

One record in a table containing information about one


Row
single entity.

A set of rows of a certain entity-type, i.e. all rows of a


Table
certain table have the same structure.

A logical unit of work consisting of one or more


Transaction
modifications to the database.

Implementation of a single data item within a


Value certain column of a certain row. (You can think of a cell
within a spread sheet.)

A virtual table containing only its definition and no real


View data. The definition consists of a query to one or more
real tables or views.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 82 of 95


Bibliography
Textbooks

 DuBois, Paul. 2013. MySQL. 5th Edition. Pearson Education. ISBN:


9780321833877.

 DuBois, P., Hinz, S. & Pedersen, C. MySQL 5 Certification Study guide.


MySQL Press. ISBN: 0672328127.

Websites

MySQL reference guide, 2014 http://dev.mysql.com/doc/refman/5.6/en/


[Accessed: 11-08-2014]

MySQL tutorials and tips, 2011 http://dba.fyicenter.com/faq/mysql/ [Accessed:


11-08-2014]

W3schools, 2014. http://www.w3schools.com/sql/ [Accessed: 11-08-2014]

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 83 of 95


MySQL Administration - Exercise Checklist
(MLMA181-01V1.0)

Student ____________________ Start date ___________________

Please note that unless all of your exercises have been signed off by the
lecturer, you will not be allowed to book for the exam.

Date Sign Date Sign

1.1.6 Revision questions 1.2.7 Revision questions


1 1
2 2
3 3
4 4
5 5
1.3.8 Revision questions 1.4.1 Revision questions
1 1
2 2
3 3
4 4
5 5
2.1.7 Revision questions 6
1 7
2 8
3 9
4 10
5 11
2.2.5 Revision questions 12
1 13
2 14
3 15
4 2.3.5 Revision questions
5 1

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 84 of 95


6 2
2.4.2 Revision questions 3
1 4
2 5
3 3.1.6 Revision questions
4 1
5 2
6 3
7 4
8 5
9 3.2.6 Revision questions
10 1
11 2
3.3.2 Revision questions 3
1 4
2 5
3 6
4 7
5

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 85 of 95


MySQL Administration – Evaluation Form
(MLMA181-01V1.0)

How would you evaluate the (MLMA181-01) learning manual? Place a  or  in one of the five
squares that best indicates your choice. Your response will help us to improve the quality of
the learning manuals and modules, and will be much appreciated.

Very poor Poor Fair Good Excellent

The learning manual is clear and


understandable.

The text is clear and understandable.

The exercises help you grasp the module


material.

The projects help you understand the


module material.

You know what to expect in the examination.

The practical exercises test your knowledge


and ability.

Your lecturer was able to help you.

What did you enjoy most?

What did you enjoy least?

General comments (what would you add, leave out, etc.?)

Please note any errors that you found in the learning manual.

Campus Lecturer Date


Please remove this evaluation form and return it to your Lecturer or senior Lecturer so that it
can be forwarded to the Division for Moduleware Development. Thank you
Alternatively, please follow the link below to evaluate the module:
CTI Education Group Module Evaluation

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 86 of 95


Note: Google Chrome browser must be installed in the device used to view the link.

MLMA181-01 - MySQL Administration Learning manual| V1.0 Oct 2016 Page 87 of 95


Contact details
Bloemfontein Campus
Bedfordview Campus
Tourist Centre, 60 Park Avenue, Willows, BloemfonteinP.O.
9 Concorde Road East, Bedfordview
Box 1015, Bloemfontein, 9300
P.O. Box 1389, Bedfordview, 2008
Tel: +27 (0)51 430 2701, Fax: +27 (0)51 430 2708Email:
Tel: +27 (0)10 595 2999, Fax: +27 (0)86 686 4950
bloemfontein@cti.ac.za
Email: bedfordview@cti.ac.za

Cape Town Campus Durban Campus


The Brookside Building, 11 Imam Haron Str 1 Lunar Row, Umhlanga Ridge, Durban
(old Lansdowne Road), Claremont P.O. Box 2325, Clareinch, P.O. Box 20251, Durban North, 4016 Tel: +27 (0)31 564
7740 Tel: +27 (0)21 674 6567, Fax: +27 (0)21 674 6599 0570/5, Fax: +27 (0)31 564 8978
Email: capetown@cti.ac.za Email: durban@cti.ac.za

Durbanville Campus
East London Campus
Kaapzicht, 9 Rogers Street, Tyger Valley P.O. Box 284, Private
12 Stewart Drive, Berea, East London PostNet Suite 373
Bag X7 Tyger Valley, 7536
Private Bag X9063, East London, 5200 Tel: +27 (0)43 721
Tel: +27 (0)21 914 8000, Fax: +27 (0)21 914 8004
2564, Fax: +27 (0)43 721 2597 Email: eastlondon@cti.ac.za
Email: durbanville@cti.ac.za
Port Elizabeth Campus
Nelspruit Campus
50 Murray Street, Nelspruit Building 4, Ascot Office Park
P.O. Box 9497, Sonpark, Nelspruit, 1206 Cnr Ascot & Conyngham Roads, Greenacres
Tel: +27 (0)13 755 3918, Fax: +27 (0)13 755 3918 P.O. Box 40049, Walmer, 6065
Email: nelspruit@cti.ac.za Tel: +27 (0)41 374 7978, Fax: +27 (0)41 374 3190
Email: port_elizabeth@cti.ac.za
Potchefstroom Campus Pretoria Campus
12 Esselen Street, Cnr Esselen Street 22 Umgazi Street, Menlo Park, Pretoria
& Steve Biko Avenue, Die Bult, Potchefstroom PostNet Suite A147, Private Bag X18,
P.O. Box 19900, Noordbrug, 2522 Lynnwood Ridge, 0040
Tel: +27 (0)18 297 7760, Fax: +27 (0)18 297 7783 Tel: +27 (0)12 348 3060, Fax: +27 (0)12 348 3063
Email: potchefstroom@cti.ac.za Email: pretoria@cti.ac.za
Group Head Office Vanderbijlpark Campus
Management Services Building Building 2, Cnr Rutherford & Frikkie Meyer Boulevards
44 Alsatian Road, Glen Austin Extension 3, Midrand Vanderbijlpark
P.O. Box 1398, Randburg, 2125 P.O. Box 6371, Vanderbijlpark, 1900
Tel: +27 (0)11 467 8422, Fax: +27 (0)86 583 6660 Tel: +27 (0)16 931 1180, Fax: +27 (0)16 933 1055
Website: www.cti.ac.za Email: vanderbijlpark@cti.ac.za

CTI is part of Pearson, the world’s leading learning company. Pearson is the corporate owner, not a registered
provider nor conferrer of qualifications in South Africa. CTI Education Group (Pty) Ltd. is registered with
the Department of Higher Education and Training as a private higher education institution under the
Higher Education Act, 101, of 1997. Registration Certificate number: 2004/HE07/004. www.cti.ac.za.

You might also like