DESIGN A DATABASE MySQL Plan Tables The first step in designing the database is to list all of the data you need to store and decide how it can be divided into tables.. Plan Columns Afte
Trang 1Á Press Ctrl-X and then Y
to save the file and exit the
editor
Note: This command will vary depending on your editor
■You are returned to the MySQL monitor
‡ Type \g and press Enter
■The monitor executes the query and displays the result
° Type SHOW TABLES; and press Enter
■The list of tables in the database is displayed, including the new table
The Windows version of the MySQL monitor does not support the
\ecommand There are several alternative ways to deal with long MySQL commands if you are using a Windows system The first is
to type the command in a text editor, such as Notepad, select it, and use the Copy command to copy it to the clipboard, and then paste
it into the MySQL monitor window.
Another alternative is to use the MySQLGUIutility, a graphical interface to MySQL, described in the next section This utility includes a text box that you can use to enter a command of any length, and then submit it to the server It also saves the most recent queries you have performed and allows you to easily repeat them.
The Windows version of the MySQL monitor can be used to connect to a MySQL server running on a UNIX system, and the UNIX version can connect to a Windows-based server While there are slight differences in the client programs, they use the same protocols to communicate with the MySQL server.
27
Trang 2■When you start MySQLGUI,
you are prompted for a
password The root user
is used by default
⁄ Enter the password and click OK
■The main MySQLGUI window is displayed
¤ Click the Options button
to configure MySQLGUI
The MySQL monitor is only one of the clients you can
use with a MySQL server You can use MySQLGUI, a
graphical MySQL client, as an alternative interface to
MySQL This utility can do most of the same things as the
MySQL monitor.
MySQLGUIwas developed by the developers of MySQL,
and is available from the Downloads section of the MySQL
Web page at www.mysql.com/ Binary versions of this utility
are available for Windows and Linux systems.
For Windows systems,MySQLGUIis distributed as a ZIP file.
You will need to use a program such as WinZip to extract
the files from the archive WinZip is available from the
following URL: www.winzip.com/.
To install MySQLGUI, simply copy the files from the ZIP
archive to a directory on your computer You can use it
from any machine that can reach your MySQL server across
the network; it does not have to be installed on the same machine as the MySQL server software.
After you have installed the files, open the directory and double-click the mysqlgui.exefile MySQLGUI prompts you for a password for the root user After you specify this once, you can click the Options button to specify a different username for future sessions.
The MySQLGUIutility is also available for Linux and several other systems, and the source code is available See the MySQL Web site for complete instructions for installing or compiling MySQLGUIon your system.
MySQLGUIallows you to send queries to the MySQL server, display the server status, and perform other tasks See Chapter 6 for information about using MySQLGUIto perform a query, and see Chapter 9 for information about server management using MySQLGUI.
CONFIGURE MYSQLGUI
MySQL
CONFIGURE MYSQLGUI
Trang 3■The MySQL client options
dialog box is displayed It is
divided into several pages;
the Server page is selected
by default
‹ On the Server page,
specify the host name for
the MySQL server
› Specify a default database
to connect to when MySQLGUI starts
ˇ Click the Client tab to switch to the next page
■The Client configuration page is displayed
Á Enter a username for the MySQL server
‡ Click Save to save the settings you have specified
■You are returned to the main MySQLGUI window
After you have configured MySQLGUI, you can use it to work with the MySQL server The main window includes a drop-down menu that allows you to select a database to work with, similar to the USE
command in the MySQL monitor There is also an indicator that is green in color if you have a valid connection to the MySQL server.
The main part of the window is divided into two sections The top area allows you to specify a MySQL query with one or more lines.
You can edit the query as needed Do not use a semicolon to end queries you enter into MySQLGUI When the query is finished, click the Execute query button to send it to the MySQL server.MySQLGUI
opens a new window to display the results of the query.
The bottom portion of the window displays a list of your most recent queries for the selected database You can click an entry in this list to copy the query to the top window, and use the Execute query button to send the query to the MySQL server again.
To exit MySQLGUI, click the Exit button on the toolbar or close its window The list of recent queries is saved and displayed again the next time you run the utility.
29
Trang 4DATABASE DESIGN BASICS
Creating a database and one or more tables is easy.
The complex part of the process is designing the
database: determining the data you need to store,
how it should be divided into tables and fields, and the type
of tables to use.
DESIGN A DATABASE
MySQL
Plan Tables
The first step in designing the database is to list all of
the data you need to store and decide how it can be
divided into tables Often separate tables are more
practical than one large table, but avoid duplicating
information between tables If you will be using
applications to work with the tables, plan accordingly
so that each application only needs to access a
minimum number of tables.
Plan Columns
After deciding on a list of tables to include in the
database, list the fields, or columns, to include in each
table and the type of data to be stored in each column.
You can add columns at a later time, but your list of
columns should be as complete as possible when you
create the tables Keep the list of columns short and to
the point; do not include unnecessary data, duplicates
of data available in another table, or fields that can be
calculated from existing fields.
Keys and Indexes
Each table will need a primary key: a unique index that
you can use to single out any record, or row, from the
table Along with the primary key, you may want to
create additional indexes, also known as secondary
keys, to make it easier for the server to find data within
columns that are frequently searched.
Relationships Often you will need to consider the relationship between two tables For example, you may have an address book table and a phone list table Each would include a name field, and you could relate data between the two tables using this field To ensure that table relationships can be taken advantage of, be sure any fields that can be used to link tables are the same type and are set up as keys to the tables.
Security Some data requires more security than other data You may need a more secure type of table to store certain data, and you may want to separate the non-critical data and the critical data In addition to security, your design should take reliability into account You may need to use multiple database servers to make data reliably available, and use regular backups to keep the data safe Plan for the Future
Along with your current needs, you should take any plans for the future into account when designing the database If you will be adding additional tables at a later time, plan the current tables to use similar columns and make relationships between tables easier One important way of preparing for future changes is to use a standard naming convention for the columns in your tables If two tables have a column that stores the same data, be sure they both use the same column name and store the data in the same format.
The process of database design includes choosing tables,
the columns that will make up the tables, and the keys,
indexes, and relationships among tables.
Trang 5MyISAM
MyISAM is the default MySQL table type This type of
table is based on the ISAM, or Indexed Sequential
Access Method, standard The main disadvantage of
MyISAM tables is that they are not transaction safe.
Transactions are used with critical data storage, such as
that used by financial institutions, to ensure that only
complete transactions are recorded in the database.
Incomplete transactions can be rolled back to prevent
corruption of the data.
Because using transactions is not necessary for most
Web database applications or for many non-critical
business uses, MyISAM tables are useful If you create a
table on the MySQL server without specifying a table
type, the MyISAM type is used by default.
ISAM
ISAM is the standard table type that MyISAM tables are
based on Because MyISAM tables are smaller and more
efficient, use of ISAM tables is discouraged by the
MySQL developers, and this type may not be supported
by future versions of MySQL You should use it only if
you need compatibility with data already in the ISAM
format.
Heap
Heap tables are specialized They use a hashed index,
which uses a mathematical formula to quickly find the
location of data for a key Heap tables are stored in
RAM rather than on disk This makes a Heap table
extremely fast, but not reliable for permanent storage.
Heap tables are a perfect choice when you need to
create a temporary table.
BDB
BDB, short for Berkeley DB, is a new table type
supported by MySQL 3.23.34 and later This table type is not supported by default when you install MySQL unless you use the MySQL-Max distribution You can compile the regular MySQL distribution to optionally include support for BDB tables.
The main advantage of BDB tables is that they support transactions You can begin a transaction, submit data, and use the COMMITcommand to commit the data to the database If the application is interrupted before the data is complete, you can use the ROLLBACKcommand
to remove the partial transaction and keep the database stable BDB is also designed for high performance when working with large amounts of data and many
concurrent users.
BDB is developed by Sleepycat Software You can find out more about this database system at the developer's Web site, www.sleepycat.com.
InnoDB
InnoDB is an industrial-strength database system that is
supported by MySQL 3.23.34a and later Like BDB, InnoDB is not supported by default; you need to compile MySQL with InnoDB support or use the MySQL-Max distribution.
Like DBD, InnoDB supports transactions, committing, and rollbacks InnoDB provides greater performance than basic MyISAM tables, especially when you are working with large amounts of data You can find out more about InnoDB at www.innodb.com.
MYSQL TABLE TYPES
MySQL supports a variety of different table types Each
database on a MySQL server can contain tables of any of
these types While the default type is sufficient for most
purposes, you should be familiar with the different types
available and know when there may be a more
appropriate choice.
You can choose the table type to use with the TYPE
keyword within a CREATE TABLEquery in MySQL You can convert a table to a different type later if needed.
Trang 6Databases are the largest unit of data on a MySQL
server Each MySQL server can store any number of
databases Each table of data is stored in one of
these databases.
CREATE AND DROP DATABASES
Database Internals
When you create a database, the MySQL server creates a
directory on the server's file system When you install
MySQL, you can choose the location for these directories.
Within each database's directory, the MySQL server
creates files for each of the tables you create in the
database.
Existing Databases
If you attempt to create a database using CREATE DATABASE, but a database with the name you specify already exists on the server, an error message is returned To avoid this error, you can use the IF NOT EXISTSkeywords with the CREATEcommand If this is specified and the database already exists, no error is returned, no new database is created, and the existing database is unchanged.
Example:
CREATE DATABASE IF NOT EXISTS newdb;
USING CREATE DATABASE
Show Database Contents
Because the DROP DATABASEcommand is drastic, use
it carefully One way to be sure you are deleting the
correct database is to use the SHOW TABLEScommand
to display a list of tables in the database Be sure none
of the tables listed contains important data.
The SHOW TABLE STATUScommand displays a more
detailed list of tables, including the number of rows
stored in each table Use this command to be sure you
are going to delete the right tables.
Example:
SHOW TABLES FROM newdb;
SHOW TABLE STATUS FROM newdb;
Data Security and Backups Because DROP DATABASEand other commands can cause drastic and immediate loss of data if not used carefully, it is always a good idea to maintain backups of important data and to make a backup before using the
DROPcommand Chapter 8 explains how to back up data on the MySQL server.
USING DROP DATABASE
MySQL
You can create a new database with the CREATE
DATABASEcommand in MySQL To use this command,
simply specify a name for the new database.
Example:
CREATE DATABASE newdb;
The DROP DATABASEcommand in SQL allows you to
delete an existing database This command immediately
deletes the database You are not asked to confirm this
action All tables within the database and the data they
contain are deleted.
Normally, using DROP DATABASEwill return an error if the database does not exist You can avoid this error by adding the phrase IF EXISTSto the DROP DATABASEquery Example:
DROP DATABASE newdb;
Trang 7⁄ From the command
prompt, type mysql and press
Enter to start the MySQL
monitor
Note: You may need to specify
a username and password when
starting the monitor See Chapter 1
for details
¤ From the MySQL monitor, type CREATE DATABASE newdb; and press Enter
■The server creates the database
‹ Type SHOW DATABASES;
and press Enter
■The complete list of databases on the server is displayed, including your new database
33
Before you can store data in tables within a MySQL
database, you must first create the database You can
do this using the CREATE DATABASEcommand in
SQL The basic form of this command simply specifies a
database name:
CREATE DATABASE newdb;
When you create a database, no tables or data are stored in
the database The MySQL server stores each database as a
directory on the server When you create a new database, a
directory is created to store its tables When you later
create one or more tables, they are stored as files within
this directory.
If you attempt to create the newdb database and a database
with that name already exists, an error message is displayed.
To avoid this error, you can specify IF NOT EXISTS This
tells the server to create the database only if it does not exist, and no error is returned:
CREATE DATABASE IF NOT EXISTS newdb;
Because the database name is used as a directory name
on the server, you can use any valid name as a directory on your system Two characters that are explicitly disallowed in database names are period (.) and slash (/) On most systems, safe characters to use in directory names include letters, numbers, and the underscore (_) Spaces are not allowed in names in some systems.
The opposite of CREATE DATABASEis the DROP DATABASEcommand This command deletes the directory structure for a database, including all tables Because it does not warn you that data will be lost,DROP DATABASE
should be used carefully.
CREATE A DATABASE
CREATE A DATABASE
Trang 8⁄ From the MySQL monitor,
type SHOW DATABASES; and
press Enter
■The complete list of
databases on the server is
displayed
Note: Depending on the databases you have created, your list will vary from the results shown here
¤ Type SHOW DATABASES LIKE '%test%'; and press Enter
■All databases containing the word 'test' are displayed
If you created the testdb database in Chapter 1,
it will be listed here
You can use the SHOW DATABASEScommand from
within the MySQL monitor to list all of the databases
available on the server The basic command is simple:
SHOW DATABASES;
You can also use the LIKEkeyword to show only databases
whose names match a pattern The following shows a list of
all databases that begin with the letter t:
SHOW DATABASES LIKE 't%';
The LIKEclause supports wildcard characters These are
useful when you are unsure of the exact name of the
database you are looking for, or when you need to list all of
the databases that match a certain keyword The first
wildcard, underscore (_), matches any character This
command would list the testdb database and any others
that contain testdfollowed by one letter:
SHOW DATABASES LIKE 'testd_';
The second wildcard is the percent (%) character This matches any string of characters, or no characters The following command would list the testdb database along with any other with a name containing 'test':
SHOW DATABASES LIKE '%test%';
Because this command includes wildcards at the beginning and end of the database name, it looks for the characters
testat any location This example would match databases named testdata, datatest, or newtest23.
Rather than using the MySQL monitor, you can also use the
mysqlshowutility, which is included with the MySQL server, to list the databases Use mysqlshowwith no parameters to list all of the databases on the server You can also specify a database name to display the tables included
in the database The following mysqlshowcommand displays the tables within the testdb database:
mysqlshow testdb
SHOW AVAILABLE DATABASES
MySQL
SHOW AVAILABLE DATABASES
Trang 9⁄ From the MySQL monitor,
type USE testdb; and press
Enter
■The database is selected.
Note: This command will only work if you have created the testdb database Follow the instructions in Chapter 1 if you need to create it
¤ Type SHOW TABLES; and press Enter
■The list of tables in the current database is displayed
35
Later in this chapter you will work with tables Before
you can work with the tables in a database, you must
first select the database You can do this with the USE
command To use this command, type USEfollowed by the
database name and a semicolon to end the statement For
example, the following command selects the testdb
database:
USE testdb;
After you have selected a database with the USEcommand,
it is used as the default database for any queries you make.
If you refer to a table in a subsequent query, the MySQL
server looks for that table in the database you previously
selected.
In order to select a database, you must be logged in to the
MySQL server using the MySQL monitor, or another client,
and the username you have specified must have permission
to access the database you select You can use the SHOW DATABASEScommand, described in the previous section,
to determine a database name to select.
As an alternative to the USEcommand, you can also specify
a database name and table name when you perform a query that involves a table You do this by separating the database name from the table name using a period For example, testdb.address refers to the address table within the testdb database.
After you have selected a database with the USEcommand, you can use commands like CREATE TABLEor SELECTto work with the current database This database remains as the default until you specify another database with USEor until you exit from the MySQL monitor or other MySQL client.
SELECT A DATABASE
SELECT A DATABASE
Trang 10CREATE AND DROP TABLES
MySQL
After creating a database on the MySQL server, you
can create one or more tables to store data Each
database can contain any number of tables.
Specify Columns
The list of columns, or fields, for the table is included in
parentheses in the CREATE TABLEcommand Column
types such as CHARand DECIMALcan have parameters
in parentheses; include these within the column list.
Commas separate the column names.
Example:
CREATE TABLE test (
Column1 INTEGER,
Column2 CHAR(50) );
Specify Column Attributes
You can specify one or more optional attributes for a
column after its column type For example, the NULLor
NOT NULLattribute indicates whether the column can
store NULLvalues.NULLis a special value that indicates
that nothing has been stored in the column.
The DEFAULTattribute specifies a default value for a
column For columns that allow NULLvalues,NULLis
the default; otherwise the default is zero for numeric
columns and a blank value for text columns If you
specify a value for the DEFAULTattribute it overrides
this default.
Example:
CREATE TABLE test2 (
Column1 CHAR(10) NOT NULL,
Column2 INT DEFAULT 10 );
Create a Unique Index or Primary Key You can use the keyword UNIQUE to create a unique index, also known as a key A unique index is similar to
a standard index, but each row’s value for the indexed column must be unique.
As with INDEX, you can specify an optional name for the index and one or more columns to be indexed When you index more than one column, only the combination of values of the columns needs to be unique A table can have any number of unique indexes.
A primary key is similar to a unique index, but each
table can have only one primary key Additionally, the primary key must have the NOT NULLattribute The primary key is used to uniquely identify each row of the table.
You can assign the primary key using the PRIMARY KEY
keywords, similar to INDEX Alternately, you can specify the PRIMARY KEYattribute for one of the columns Example:
CREATE TABLE phonelist ( name VARCHAR(20) NOT NULL, phone VARCHAR(12),
UNIQUE phoneindex (phone), PRIMARY KEY (name) );
Create Indexes
When you index a table, the server stores a list of values
and pointers into the database to make it easier to
search for values in the indexed columns You can
create a simple index with the INDEXkeyword You can
specify an optional name for the index and one or more
columns to index in parentheses.
Example:
CREATE TABLE clients ( name VARCHAR(20), city VARCHAR(30), INDEX index1 (name,city) );
CREATE TABLES
You can use the CREATE TABLEcommand to create a table As
with the CREATE DATABASEcommand, this command normally
returns an error if the table already exists If you use the optional
keywords IF NOT EXISTS, this error is suppressed.