1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu MySQL Administrator’s Bible- P3 ppt

50 272 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Accessing MySQL
Thể loại tài liệu
Định dạng
Số trang 50
Dung lượng 2,87 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Among the tasks you canperform are: ■ Create new tables ■ Manage table indexes ■ Manage users ■ Synchronize databases ■ Back up and restore databases ■ Create triggers, views, events, an

Trang 1

the server host and themysqldinstance If you experience any problems SQLyog has very ough, context-sensitive help Figure 3-1 shows this connection dialog.

thor-FIGURE 3-1

SQL query creation

SQLyog has two methods of SQL query creation With the first method you type the query in aquery building window SQLyog provides two tools to assist you — the auto-completion featureand SQL templates.mysqldoes not have tab completion on Windows (see the previous section

onmysqlfeatures) With SQLyog you can use the Tab key to complete table or column names

or even functions, no matter what operating system you are using SQL templates help with theproper syntax for the various SQL commands First, right-click in the query building window.This will bring up a menu where you left-click Insert Templates to use a template Figure 3-2shows the list of available templates with theCREATE TRIGGERstatement template selected

At this point you just click the Insert button and SQLyog will create the template for you to fill

in with your specific data

The second method of query writing is using the query builder to create the query This is

a more graphical method of query building where you drag the appropriate tables from theschema objects to a blank window You can then do the common query actions of joiningtables, sorting, filtering, and grouping based on your chosen criteria SQLyog will then build theSQL command for you to execute without actually having to type any SQL code

Figure 3-3 shows how the query builder looks with a simple query built from thesakila

database

Trang 2

FIGURE 3-2

FIGURE 3-3

Trang 3

After building the query you can copy the query over to the Query tab and then execute it withjust a couple of clicks.

Database management

SQLyog has numerous features designed for database management Among the tasks you canperform are:

■ Create new tables

■ Manage table indexes

■ Manage users

■ Synchronize databases

■ Back up and restore databases

■ Create triggers, views, events, and stored procedures

Database synchronization

One of the best features of SQLyog is the database synchronization with its powertool This tool

allows you to synchronize two different databases by creating the corresponding SQL commandsneeded to match both the structure and data of the two database tables There is a wizard thatwill guide through each step of the process The process is simple — just select the databasesand tables to synchronize and SQLyog takes care of everything else Resolving a data synchro-nization problem by hand is incredibly difficult, and SQLyog reduces the complexity to a fewsimple clicks

phpMyAdmin

phpMyAdmin is a free set of PHP scripts that are used to manage a MySQL server via a webinterface Because phpMyAdmin is based on these PHP scripts it does require a web server torun Though this might be seen as a drawback, it also means that you can access your MySQLservers from any computer that has a web browser phpMyAdmin can be used to manage anentire MySQL server or a single database

You can find more information about phpMyAdmin, including how to download the program, at http://www.phpmyadmin.net/

We are not going to show how to install phpMyAdmin for your server setup because it variesdepending on your operating system Typically, it is not very difficult Once done with theinstallation of phpMyAdmin, access the system by simply going to the following URL in yourbrowser:http://yourserverip/phpmyadmin You will need to replaceyourserveripwiththe hostname or IP address of your web server You will be presented with a login screen whereyou will input your MySQL server login credentials

Trang 4

Figure 3-4 shows the opening screen for phpMyAdmin once you log in.

sim-Creating a table in your database

Creating a table is almost as easy as creating a database Just click the database you created inthe navigation frame and a new window will appear on the right-hand side of the split screen

To create a table you just use the Create New Table option You should enter the name of thenew table into the Name field, and the number of expected fields for the table into Fields

At this point, after you click Go, you just fill in the information for the columns in your newtable Once you are done with configuration, clicking the Save button will create your new table

Trang 5

Data insertion into a table

Once your table is configured you can fill it with data using phpMyAdmin On the screen that

is displayed after you create a table there is an Insert tab Click this and another screen shouldappear This screen is your data entry screen When you are done with a record just click Saveand it will be saved to the table

After you click Save, the record is saved to the testing table, and the data entry screen is shownagain You can insert more records by selecting Insert again If you are going to be insertingmultiple records it is faster if you select the Insert Another New Row radio button on theinput form

Database backup

Backing up databases is easy with phpMyAdmin You select the database you want to back up

by clicking the database name in the left-hand navigation bar Next you click the Export buttonand then make sure all tables are highlighted that you want to back up

You can then specify the options you want under Export Make sure that you enter a filename

so you can save the output In the background phpMyAdmin is using themysqldumpprogram,which is covered in Chapter 13

The phpMyAdmin program has a fairly user-friendly interface Because it is used by a number ofweb-hosting providers, many administrators are at least somewhat familiar with it Although ithas a modest range of abilities, it does have some flexibility in that you can access the programfrom anywhere with a web browser It should be pointed out, as we discuss in Chapter 20, thatrunning both a web server and a database server on the same server increases your security risk.Sharing resources means there will be fewer available formysqld Think very carefully beforeinstalling phpMyAdmin on the same machine asmysqld

MySQL Query Browser

The Query Browser is part of the GUI bundle that MySQL has available for free downloadfromhttp://dev.mysql.com/downloads/gui-tools Also included in this bundle are theMySQL Administrator tool (discussed in the following section) and the MySQL Migration Tool,which we will not be covering The Query Browser and other associated tools are available forWindows, Macintosh OS X, and Linux so it allows for a good degree of cross-platform usage

The Query Browser is a GUI tool for creating, executing, and optimizing queries

The Query Browser includes the following components:

■ Query Toolbar: Create small queries and execute them Browse old queries

■ Script Editor: Useful for editing more complex queries

Trang 6

■ Results Window: Displays query results.

■ Database Explorer: Navigate, create, and drop tables and fields

The central interface of the Query Browser provides access to all of the preceding functionality.This window is also customizable by allowing you to control which toolbars are present TheQuery History functionality combined with navigation buttons allows you to browse your queryhistory and re-execute queries with or without editing them

To begin a Query Browser session you have to establish a connection to your server When youstart Query Browser you see the screen in Figure 3-5

pre-Once you have established your connection to the server you are presented with the main QueryBrowser screen, which is shown in Figure 3-6

Looking on the right-hand side of the screen you can see the databases on the connected server

In this case you can see theinformation_schemaandmysqldatabases (used by the MySQLserver) and atestdatabase Also there is thesakiladatabase, which you will be using for theexample

Trang 7

FIGURE 3-6

To work with thesakiladatabase a single mouse-click on the arrow to the left of thesakila

database icon will display all the tables Just enter the query to execute and click the Executebutton to the right of query entry screen Once you enter the query and execute it the resultsare shown in the results pane on the bottom left of the screen, as shown in Figure 3-7

After you have entered multiple queries you can use the Go Back and Next buttons to browsethrough the history of the already executed queries

Under the Tools menu you can start MySQL Administrator, themysqlcommand-line client,the Windows command line (if you are on Windows), a text importer (that uses regularexpressions), and the connections manager, where you can save connection information

You can also manage stored routines very easily with Query Browser This might be one of thebest features of Query Browser because it is very difficult to manage a stored routine from theMySQL command line (see Chapter 7 for more information about stored routines) Though

a procedure or function can be programmed from the command line, it is awkward at best

A graphical environment such as Query Browser makes it much easier to work with storedprocedures and functions

Trang 8

FIGURE 3-7

To begin a new stored procedure, make sure you have a database selected and then just clickScript and then Create Stored Procedure/Function Once you have created the stored procedure

or function you will be presented with the editing screen as shown in Figure 3-8

All of the initial setup is already done for you Just write your query and click the Execute ton to store it on the server You can also examine and edit stored procedures and functions thatare already created To do this just click Script on the menu bar and select Edit All Stored Pro-cedures/Functions Figure 3-9 shows what this looks like

but-Now you just edit the appropriate procedure and click Execute to reload the procedures.The Query Browser program is well rounded with only one major weakness: Though it is morespecialized than the other programs covered here, it is designed to work in tandem with theMySQL Administrator program covered in the next section

MySQL Administrator

The MySQL Administrator is included in the same bundle with the Query Browser It is across-platform tool that runs on Windows, Linux, and the Mac OS X MySQL Administrator is aGUI console that enables you to administer amysqldserver instance

Trang 9

FIGURE 3-8

FIGURE 3-9

Trang 10

Some of the functionality that MySQL Administrator allows includes:

■ User management

■ Monitoring database health

■ Performing backups and restores

■ Managing server logs

■ Monitoring server connectionsThe connection dialog is the same as for Query Brower Once you have established your connec-tion to a server the main screen will look similar to what is shown in Figure 3-10

FIGURE 3-10

This is the central control panel used to manage your servers On the left-hand panel you cansee the icons that are used to access the screens for specific functions

Trang 11

User administration

MySQL Administrator makes creating users, dropping users, granting privileges, and seeing ileges quite easy Using an intuitive form you can add users, set passwords, and specify moreinformation about the user Figure 3-11 shows the user administration screen

priv-FIGURE 3-11

As you can see there are two tabs in the right-hand pane The first tab (User Information) isused to enter the basic login credentials and details about the user such as name and e-mail TheSchema Privileges tab is used to both assign and remove global, database, and table/column-levelprivileges

There is a list of the system users in the lower-left part of the screen To view and edit thecurrent information on a user just click the username Then you will be able to edit theproperties on the right-hand side of the screen Once you are done just click Apply Changes

With a reasonable layout this screen makes it very easy to edit a user’s password or schemaprivileges

Trang 12

Health monitoring

The health monitoring screen gives you a view into the activity of your MySQL server Very nicegraphing functionality shows you:

■ The percentage of memory used

■ The number of current connections

■ The number of SQL queries being executedThis provides both an immediate view of system activity, plus a more long-term view as it keepstrack of statistics as long the Administrator is running Figure 3-12 shows the Health monitoringscreen

FIGURE 3-12

Trang 13

Although this is a nice feature it does require that the MySQL Administrator program be nected to the database server for extended periods of time if you want to gather long-term statis-tics Chapter 19 covers various programs that can be used for monitoring your database

con-servers

Backup and recovery

With the backup and recovery screen, you can create backups and restore data using a cal interface You can choose to back up an entire database or one or more tables by clicking oncheck boxes This screen looks fancy, but it is actually simply providing a nice interface to the

graphi-mysqldumpprogram, which is covered in Chapter 13 We also cover general background aboutwhy it’s important to back up your servers and other topics such as how often you should back

up Figure 3-13 shows the backup screen with thesakiladatabase chosen to backup

FIGURE 3-13

Trang 14

Server log management

On the server log management screen, you can view all the log files — error logs, binary logs,and slow query logs This can help you when troubleshooting server issues

Service control

When your database servers are running on Microsoft Windows, MySQL Administrator allowsyou to control service creation and automatically creates, installs, and configures servicesthrough the service control screen You can even use MySQL Administrator to start and stopyour server

Catalogs

The catalogs screen allows you to browse your databases and corresponding table informationavailable about columns and indexes, views, and even stored procedures From this screen youcan perform basic table maintenance such as optimizing and checking tables Figure 3-14 showsthis screen for thesakiladatabase

Overall the MySQL Administrator provides a decent program to help with server tion The Query Browser is the stronger of the two related programs Both programs are avail-able fromhttp://dev.mysql.com/downloads/gui-tools

As an example of what can be done with MySQL Workbench we reverse engineered the

sakiladatabase This entire process took about five minutes Figure 3-15 is what you see whenyou start up the Workbench program

Trang 15

FIGURE 3-14

FIGURE 3-15

Trang 16

FIGURE 3-16

Now that you have the program started, select Database from the menu and then ReverseEngineer This will bring up the connection screen where you have to fill in the hostname, user-name, and password used to access the server You need to make sure that you have permission

to access the server you are trying to reverse engineer Figure 3-16 shows the connection screen.Once you have established the connection to the server, the next screen will allow you to select(by default) all the tables or any number of individual tables

Once you have selected the desired tables it is just a matter of having MySQL Workbenchconstruct the Entity Relationship (ER) diagram As the server builds the diagram it will ask if

it should automatically place the tables on the diagram We recommend that you choose thisoption Once the initial diagram is built you can then rearrange them to your heart’s content.You can print the ER diagram directly or export to a PDF file Figure 3-17 shows thesakila

database after being reverse engineered

Trang 17

FIGURE 3-17

Reverse engineering a database is easy with the proper tools If you have a significant number oftables it might take some time to arrange the tables in your ER diagram as you want, but thatthis is much faster than building the ER diagram by hand In the preceding figure, the lines onthe diagram represent the foreign key relationships between the tables

Summary

Any database administrator should to take the time first to learn themysqlclient, because it

is the default access client and will always be available The other tools, both GUI-based andcommand-line–oriented, certainly have a place in many environments Some tasks can be muchmore difficult with command-line tools or even impossible, such as with ER diagramming

This chapter covered:

■ MySQL command-line tools including:

■ Themysqlclient

■ Themysladmintool

■ Themysqlshowtool

Trang 18

■ GUI tools for MySQL administration including:

Trang 19

Developing with

MySQL

IN THIS PART

Chapter 4 How MySQL Extends and Deviates From Standard SQL

Chapter 5 MySQL Data Types Chapter 6 MySQL Index Types Chapter 7 Stored Routines, Triggers, and Events Chapter 8

MySQL Views Chapter 9 Transactions in MySQL

Trang 21

and Deviates from SQL

IN THIS CHAPTER

Learning MySQL language Structure

Understanding MySQL deviations

Using MySQL extensions

MySQL was originally designed with three basic ideas in mind:

to be fast, reliable, and easy to use Like every database system,MySQL does not completely follow the SQL standard and has itsown extensions to SQL Some very basic SQL standards, however, did notexist for a very long time — the data dictionary was only added in MySQL5.0, released in October 2005

MySQL became popular because of its relative ease of use For example,the SQL standard way of finding out which tables are in thesakila

database is:

SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=’sakila’;

The easiest way to find out this information in MySQL is:

SHOW TABLES FROM sakila;

Most of the differences from standard SQL and SQL extensions in MySQLcome from the desire to make the database system easy to use In the pastseveral years, there has been more of a commitment to support the currentSQL standard — as of the time of the writing of this book, that standard isthe ANSI/ISO SQL:2003 standard When we refer to ‘‘the SQL standard’’ or

‘‘standard SQL,’’ we are referring to ANSI/ISO SQL:2003

For information on the different SQL modes supported, see Chapter 5

Trang 22

Using the Sample Database

In Chapter 3, you imported thesakilasample database Throughout this chapter and the rest ofthe book, we will be using thesakilasample database to demonstrate database features The

sakilasample database was created by Mike Hillyer and contains data that might be found in avideo rental store For the purpose of our examples, we refer to a fictional video store whose data

is stored in thesakiladatabase and whose owner, Ziesel Skelley, uses a MySQL backend to storeand query her company’s information

Learning MySQL Language Structure

Before getting into the extensions to SQL and deviations from SQL, there are some importantrules to know about some of the language structure in MySQL, specifically relating to:

■ Comments and portability

ON the WEBSITE

ON the WEBSITE If you are new to SQL, there is an SQL Primer on the accompanying website for this book at www.wiley.com/go/mysqladminbible.

Comments and portability

One of the cleverest MySQL extensions to the SQL standard is actually a way to manageportability In some cases, portability of the schema and queries is desired, but being able touse MySQL-specific extensions when the environment is right is also desired MySQL has anextension that specifies a MySQL version as part of a comment The comment will be onlyparsed if themysqldserver is of an appropriate version; otherwise, the comment will be left as

a comment and ignored by other databases andmysqldversions

The is the standard SQL simple comment introducer Everything on a line after this is ered a comment The SQL standard bracketed comment introducer and terminator/* */allow

Trang 23

consid-partial line and multi-line commenting Putting!after the bracketed comment introducer cates that this is MySQL specific code, and themysqldserver will parse it:

indi-/*! SHOW DATABASES */;

Themysqldserver will parse theSHOW DATABASESstatement, but other database systems willnot — that is, if the other database systems follow the SQL standard for comments A five-digitnumber after the!can be used to specify a minimummysqldversion The first digit of thenumber is the major version, the next two digits are the minor version, and the last two digitsare the revision number For example, the output ofmysqldump sakilastarts with:

MySQL dump 10.13 Distrib 6.0.8-alpha

Host: localhost Database: sakila - Server version 6.0.8-alpha

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;

/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;

/*!40101 SET NAMES utf8 */;

/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

This means thatmysqldversions 4.1.1 and higher will apply the first statement, andmysqld

versions 4.1.11 and higher will apply the last statement A comment that will only be applied to

mysqldversions 6.0.8 and higher begins with/*!60008.While this syntax makes the code portable, it does not guarantee that the code will work

as expected For example,mysqldumpexports tables in alphabetical order TheSET FOREIGN_KEY_CHECKS=0statement is utilized so that a table with a foreign key con-straint can be imported even if the referencing table has not yet been created Attempting toimport this on a different database server should result in an error, because a reference is beinggenerated to a table that does not exist

MySQL extends commenting by parsing anything after an unquoted, unescaped#as a comment,regardless of whitespace around the#:

mysql> SELECT#example of # as a comment -> 0;

Trang 24

| 0 | + -+

| 0 | + -+

1 row in set (0.00 sec)

See the ‘‘Escape characters’’ and ‘‘Naming limitations and quoting’’ sections in this chapter formore information on escaping and quoting characters

Case-sensitivity

Traditionally, SQL reserved words are written in uppercase, such asSELECT,FROM,NULL, and

AS These words are case-insensitive, meaning thatSELECT,select, andSeLeCtare all parsed

bymysqldas the same reserved word Throughout this book, we will format reserved words inuppercase, even thoughmysqldwill properly parse reserved words regardless of case

In general,mysqldis case-insensitive with respect to names of fields, indexes, stored routinesand events However,mysqldstores information on the file system and makes assumptionsbased on the files and directories found on the file system For example,mysqldassumes thatany directory in the data directory (datadir) is a database This means that a directory with apath of datadir/backupwill show up as a database namedbackupwhenSHOW DATABASES

is run — whether or notbackupwas intended to be a database All tables must have a.frm

format file within the directory that represents the database they belong to; otherwise,mysqld

does not recognize the table as existing

MyISAM tables are defined by a.frmformat file, a.MYDdata file, and a.MYIindex file (seeChapter 11 for more information on MyISAM tables) It is possible to move a MyISAM table to

a different database by moving the associated files to a different directory It is also possible torename a MyISAM table by renaming the associated files However, it is not recommended thatyou make these types of changes To change the database of themove_metable fromtestto

test2, issue the statement:

ALTER TABLE test.move_me RENAME test2.move_me;

To change the name of themove_metable tokeep_me, issue:

ALTER TABLE move_me RENAME keep_me;

It is not necessarily harmful to have a directory appear as a database (such as a

lost+found directory) However, this may lead to errors with code that ically traverse all databases, such as a custom backup script It is important to be extremely careful when deleting and moving directories and files within the data directory and dropping databases.

automat-The waymysqldstores information on the file system has the consequence that some namesare case-sensitive, if the file system is case-sensitive Unix has a case-sensitive file system, and

Trang 25

Windows has a case-insensitive file system Mac OS X uses a case-insensitive file system bydefault, although it supports other, case-sensitive file systems Case-sensitivity for names isdetermined by whether or not the file system is case-sensitive for the following:

■ Log file groups

In general, there should not be problems unless the databases are used on different filesystems, for example when migrating from one file system to another The static, global

lower_case_table_namessystem variable can be set to change the default behavior of

mysqld:

■ Iflower_case_table_names=0is set, table and database names are stored usingthe case specified in theCREATEstatement In queries, table names, table aliases, anddatabase names are case-sensitive This is the default value on Unix, where the file system

is case-sensitive

■ Iflower_case_table_names=1is set, table and database names are stored using case In queries, table names, table aliases, and database names are case-insensitive — theyare actually converted to lowercase bymysqld This is the default value on Windows,where the file system is case-insensitive

lower-■ Iflower_case_table_names=2is set, most table and database names are stored usingthe case specified in theCREATEstatement The exception is InnoDB table names, whichare stored using lowercase In queries, table names, table aliases, and database names arecase-insensitive — they are converted to lowercase bymysqld, as they are when the value

is set to 1 This is the default value on Mac OS X

Come up with a naming convention that includes rules about case For example, haps databases and tables will be all lowercase, with underscores to show different words (such as in table_name) and fields will use camelCase (such as in fieldName) In this way, the issue of case is resolved, no matter what platform is being used.

per-Escape characters

The escape character is the backslash (\) An escape sequence is a backslash followed by one

character Chapter 3 discussed some commands that looked like escape sequences such as\P

and\u— these are actually translated into other commands by themysqlcommand line client.However,mysqldhas actual escape sequences, which are independent of themysqlcommands

Ngày đăng: 24/12/2013, 17:15

TỪ KHÓA LIÊN QUAN