Sample Chapter
Sample Chapter
3
Using MySQL Client Programs
Questions on the material in this chapter make up approximately 10% of the exam.
This chapter discusses general principles that are common to most MySQL client programs.
It also describes how to use several specific types of clients:
n The interactive graphical client MySQLCC (MySQL Control Center). This general-
purpose client provides a graphical interface to the MySQL server. It can be thought of
as an extended graphical version of the character-based mysql client.
MySQLCC is still being actively developed at the time of publication of the first Core
exam. For that reason, you are expected to be familiar with the general properties and
capabilities of MySQLCC, but you are not expected to know all the ins and outs of the
program.
04 6329 ch03 3/16/04 4:22 PM Page 30
n The character-based client programs. These run either interactively or perform their
job based on command-line arguments with no further input from the user. Character-
based clients discussed in this chapter include:
n mysql, a general-purpose client for issuing queries and retrieving their results. It
can be used interactively or in batch mode to read queries from a file.
n mysqladmin, an administrative client that helps you manage the server.
n mysqlimport, a program for importing text files into databases. It provides a
command-line interface to the LOAD DATA INFILE SQL statement.
n mysqldump,a program for dumping the contents of databases. It can be used to
make database backups or to copy databases to other machines.
n mysqlcheck and myisamchk, programs for checking and repairing tables. They’re
useful for checking and maintaining the integrity of certain types of tables.
n The MySQL Connector drivers. These drivers provide connectivity to the MySQL
server for client programs:
n MySQL Connector/ODBC, the MySQL driver for programs that use the ODBC
(Open Database Connectivity) interface.
n MySQL Connector/J, the MySQL driver for JDBC connectivity to Java programs.
Most examples in this section use the mysql program, but the general principles apply to
other MySQL client programs as well.
To determine the options supported by any MySQL program, invoke the program with the
--help option. For example, to find out how to use mysql, use this command:
shell> mysql --help
04 6329 ch03 3/16/04 4:22 PM Page 31
To determine the version of a program, use the --version option. For example:
shell> mysql --version
mysql Ver 12.22 Distrib 4.0.18, for apple-darwin7.2.0 (powerpc)
This output indicates that the mysql client is from MySQL version 4.0.18.
In many cases, a given option has both a long and a short form. For example, to display a
program’s version number, you can use the long --version option or the short -V option.
These two commands are equivalent:
shell> mysql --version
shell> mysql -V
Options are case sensitive. --version is recognized by MySQL programs, but lettercase vari-
ations such as --Version or --VERSION are not. This applies to short options as well. -V and
-v are both legal options, but mean different things.
Some options are followed by values. For example, when you specify the --host or -h option
to indicate the host machine where the MySQL server is running, you must follow the
option with the machine’s hostname. For a long option, separate the option and the value by
an equal sign (=). For short options, the option and the value can be, but need not be, sepa-
rated by a space. The following three option formats are equivalent; each one specifies
myhost.example.com as the host machine where the MySQL server is running:
--host=myhost.example.com
-h myhost.example.com
-hmyhost.example.com
In most cases, if you don’t specify an option explicitly, a program will use a default value.
Default values make it easier to invoke MySQL client programs because you need specify
only those options for which the defaults are unsuitable. For example, the default server
hostname is localhost, so if the MySQL server to which you want to connect is running on
the local host, you need not specify --host or -h at all.
04 6329 ch03 3/16/04 4:22 PM Page 32
Exceptions to these option syntax rules are noted in the following discussion wherever rele-
vant. The most important exception is that password options have a slightly different behav-
ior than other options.
This option specifies the machine where the MySQL server is running. The value can
be a hostname or an IP number. The hostname localhost means the local host (that is,
the computer on which you’re running the client program). On Unix, localhost is
treated in a special manner. On Windows, the value . also means the local host and
is treated in a special manner as well. For a description of this special treatment, refer
to the discussion of the --socket option.
The default host value is localhost.
n --port=port_number or -P port_number
This option indicates the port number to which to connect on the server host; it applies
only to TCP/IP connections. TCP/IP is used unless you connect using a hostname
value of . on Windows or localhost on Unix.
The default MySQL port number is 3306.
n --socket=socket_name or -S socket_name
This option’s name comes from its original use for specifying a Unix domain socket file.
On Unix, for a connection to the host localhost, a client connects to the server using a
Unix socket file. This option specifies the pathname of that file.
04 6329 ch03 3/16/04 4:22 PM Page 33
On Windows, the --socket option is used for specifying a named pipe. For Windows
NT-based systems that support named pipes, a client can connect using a pipe by speci-
fying . as the hostname. In this case, --socket specifies the name of the pipe. Pipe
names aren’t case sensitive. (Note that NT-specific MySQL servers don’t enable named
pipe connections by default; the server must be started with the --enable-named-pipe
option.)
If this option is omitted, the default Unix socket file pathname is /tmp/mysql.sock and
the default Windows pipe name is MySQL.
Two options provide identification information. These are the username and password of
the account that you want to use for accessing the server. The server will reject a connection
attempt unless you provide values for these parameters that correspond to an account that
the server recognizes:
n --user=user_name or -u user_name
This option specifies the username for your MySQL account. To determine which
account applies, the server uses the username value in conjunction with the name of the
host from which you connect. This means that there can be different accounts with the
same username, which can be used for connections from different hosts.
On Unix, client programs use your system login name as your default MySQL account
username. On Windows, the default MySQL account name is ODBC.
n --password=pass_value or -ppass_value
This option specifies the password for your MySQL account. There is no default pass-
word. If you omit this option, your MySQL account must be set up to allow you to
connect without a password.
MySQL accounts are set up using the GRANT statement, which is discussed in the
“Professional Study Guide.”
Password options are special in two ways, compared to the other connection parameter
options:
n You can omit the password value after the option name. This differs from the other
connection parameter options, each of which requires a value after the option name. If
you omit the password value, the client program will prompt you interactively for a
password, as shown here:
shell> mysql -p
Enter password:
When you see the Enter password: prompt, type in your password and press Enter.
The password isn’t echoed as you type, to prevent other people from seeing it.
04 6329 ch03 3/16/04 4:22 PM Page 34
n If you use the short form of the password option (-p) and give the password value
on the command line, there must be no space between the -p and the value. That is,
-ppass_val is correct, but -p pass_val is not. This differs from the short form for other
connection parameter options, where a space is allowed between the option and its
value. (For example, -hhost_name and -h host_name are both valid.) This exceptional
requirement that there be no space between -p and the password value is a logical
necessity of allowing the option parameter to be omitted.
Another option that affects how the connection setup occurs is --compress (or -C). This
option causes data sent between the client and the server to be compressed before transmis-
sion and uncompressed upon receipt. The result is a reduction in the number of bytes sent
over the connection, which can be helpful on slow networks. The cost is additional compu-
tational overhead for both the client and server to perform compression and uncompression.
--compress and -C take no value after the option name.
Here are some examples that show how to specify connection parameters:
n Connect to the server using the default hostname and username values with no pass-
word:
shell> mysql
n Connect to the server on the local host with a username of myname, asking mysql to
prompt you for a password:
shell> mysql --host=localhost --password --user=myname
n Connect with the same options as the previous example, but using the corresponding
short option forms:
shell> mysql -h localhost -p -u myname
n Connect to the server at a specific IP address, with a username of myname and password
of mypass:
shell> mysql --host=192.168.1.33 --user=myname --password=mypass
n Connect to the server on the local host, using the default username and password and
compressing client/server traffic:
shell> mysql --host=localhost --compress
Options in option files are organized into groups, with each group preceded by a [group-
name] line that names the group. Typically, the group name is the name of the program to
which the group of options applies. For example, the [mysql] and [mysqldump] groups are for
options to be used by mysql and mysqldump, respectively. The special [client] group can be
used to specify options that you want all client programs to use. A common use for the
[client] group is to specify connection parameters.
To write an option in an option file, use the long option format that you would use on the
command line, but omit the leading dashes. Here’s a sample option file:
[client]
host = myhost.example.com
compress
[mysql]
safe-updates
In this example, the [client] group specifies the server hostname and indicates that the
client/server protocol should use compression for traffic sent over the network. Options in
this group apply to all standard clients. The [mysql] group applies only to the mysql pro-
gram. The group shown indicates that mysql should use the --safe-updates option.
Note that if an option takes a value, spaces are allowed around the = sign, something that
isn’t true for options specified on the command line.
Where an option file should be located depends on your operating system. The standard
option files are as follows:
n On Windows, programs use the my.ini file in the Windows directory and the
C:\my.cnf file.
n On Unix, the file /etc/my.cnf serves as a global option file used by all users. You can
set up your own option file by creating a file named .my.cnf in your home directory.
To use an option file, create it as a plain text file using an editor. Client programs can access
options from multiple option files, if they exist. It isn’t an error for an option file to be
missing.
To create or modify an option file, you must have write permission for it. Client programs
need only read access.
To tell a program to read a specific option file instead of the standard option files, use the
--defaults-file option. For example, to use the file C:\my-opts for mysql on Windows,
invoke the program like this:
shell> mysql --defaults-file=C:\my-opts
If you use --defaults-file, it must be the first option after the command name.
04 6329 ch03 3/16/04 4:22 PM Page 36
If a program finds that an option is specified multiple times, either in the same option file or
in multiple option files, the option value that occurs last takes precedence. Options specified
on the command line take precedence over options found in option files.
For the mysql client, a database name on the command line is optional. This is because you
can explicitly indicate the database name for any table when you issue queries. For example,
the following statement selects rows from the table Country in the world database:
mysql> SELECT * FROM world.Country;
To select or change the default database while running mysql, issue a USE db_name statement,
where db_name is the name of the database you’d like to use. For example, the following
statement makes world the default database:
mysql> USE world;
The advantage of selecting a default database with USE is that in subsequent queries you can
refer to tables in that database without having to specify the database name. For example,
with world selected as the default database, the following SELECT statements are equivalent,
but the second is easier to write because the table name doesn’t need to be qualified with the
database name:
mysql> SELECT * FROM world.Country;
mysql> SELECT * FROM Country;
You can also provide a database name to select that database as the default database:
shell> mysql -u user_name -p -h host_name database_name
After mysql has connected to the MySQL server, it prints a mysql> prompt to indicate that
it’s ready to accept queries. To issue a query, enter it at the prompt. Complete the query
with a statement terminator (typically a semicolon). The terminator tells mysql that the
statement has been entered completely and should be executed. When mysql sees the
terminator, it sends the query to the server and then retrieves and displays the result. For
example:
mysql> SELECT DATABASE();
+------------+
| DATABASE() |
+------------+
| world |
+------------+
A terminator is necessary after each statement because mysql allows several queries to be
entered on a single input line. mysql uses the terminators to distinguish where each query
ends, and then sends each one to the server in turn and displays its results:
mysql> SELECT DATABASE(); SELECT VERSION();
+------------+
| DATABASE() |
+------------+
| world |
+------------+
+------------+
| VERSION() |
+------------+
| 4.0.18-log |
+------------+
Statement terminators are necessary for another reason as well: mysql allows a single query
to be entered using multiple input lines. This makes it easier to issue a long query because
you can enter it over the course of several lines. mysql will wait until it sees the statement
terminator before sending the query to the server to be executed. For example:
mysql> SELECT Name, Population FROM City
-> WHERE Country = ‘IND’
-> AND Population > 3000000;
04 6329 ch03 3/16/04 4:22 PM Page 38
+--------------------+------------+
| Name | Population |
+--------------------+------------+
| Mumbai (Bombay) | 10500000 |
| Delhi | 7206704 |
| Calcutta [Kolkata] | 4399819 |
| Chennai (Madras) | 3841396 |
+--------------------+------------+
More information about statement terminators can be found in section 3.2.3, “Statement
Terminators.”
In the preceding example, notice what happens when you don’t complete the query on a sin-
gle input line: mysql changes the prompt from mysql> to -> to indicate that it’s still waiting
to see the end of the statement. The full set of mysql prompts is discussed in section 3.2.4,
“The mysql Prompts.”
If a statement results in an error, mysql displays the error message returned by the server:
mysql> This is an invalid statement;
ERROR 1064: You have an error in your SQL syntax.
If you change your mind about a statement that you’re composing, enter \c and mysql will
return you to a new prompt:
mysql> SELECT Name, Population FROM City
-> WHERE \c
mysql>
The \G sequence also terminates queries, but causes mysql to display query results in a dif-
ferent style. The new style shows each output row with each column value on a separate
line:
mysql> SELECT VERSION(), DATABASE()\G
*************************** 1. row ***************************
VERSION(): 4.0.18-log
DATABASE(): world
The \G terminator is especially useful if a query produces very wide output lines. It can
make the result much easier to read.
The mysql> prompt is the main (or primary) prompt. It signifies that mysql is ready for you
to begin entering a new statement.
The other prompts are continuation (or secondary) prompts. mysql displays them to indicate
that it’s waiting for you to finish entering the current statement. The -> prompt is the most
generic continuation prompt. It indicates that you have not yet completed the current state-
ment, for example, by entering ; or \G. The ‘>, “>, and `> prompts are more specific. They
indicate not only that you’re in the middle of entering a statement, but that you’re in the
middle of entering a single-quoted string, a double-quoted string, or a backtick-quoted
identifier, respectively. When you see one of these prompts, you’ll often find that you have
entered an opening quote on the previous line without also entering the proper closing
quote.
If in fact you did mistype the current query by forgetting to close a quote, you can cancel
the query by entering the closing quote followed by the \c clear-query command.
Notice that there are no quotes around the name of the file.
mysql executes the queries in the file and displays any output produced.
The file must be located on the client host where you’re running mysql. The filename must
either be an absolute pathname listing the full name of the file, or a pathname that’s speci-
fied relative to the directory in which you invoked mysql. For example, if you started mysql
on a Windows machine in the C:\mysql\ directory and your script file is my_commands in the
C:\scripts directory, either of the following SOURCE commands would tell mysql to run the
file:
mysql> SOURCE C:\scripts\my_commands;
mysql> SOURCE ..\scripts\my_commands;
The other way to execute a script file is by naming it on the mysql command line. Invoke
mysql and use the < input redirection operator to specify the file from which to read query
input:
shell> mysql db_name < input_file
04 6329 ch03 3/16/04 4:22 PM Page 41
If a statement in a script file fails with an error, mysql ignores the rest of the file. To execute
the entire file regardless of whether errors occur, invoke mysql with the --force or -f
option.
A script file can itself contain SOURCE commands to execute other files. But be careful not to
create a SOURCE loop. For example, if file1 contains a SOURCE file2 command, file2 should
not contain a SOURCE file1 command.
In batch mode, you can use the --raw or -r option to suppress conversion of characters such
as newline and carriage return to escape-sequences like \n or \r. In raw mode, the characters
are printed literally.
To select a different output format than either of the default formats, use these options:
n --html or -H
Produce output in HTML format.
n --xml or -X
Produce output in XML format.
mysql> STATUS;
--------------
mysql Ver 12.22 Distrib 4.0.18, for apple-darwin7.2.0 (powerpc)
A full list of mysql commands can be obtained using the HELP command.
mysql commands have both a long form and a short form. The long form is a full word
(such as SOURCE, STATUS, or HELP). The short form consists of a backslash followed by a single
character (such as \., \s, or \h). The long forms may be given in any lettercase. The short
forms are case sensitive.
Unlike SQL statements, mysql commands cannot be entered over multiple lines. For exam-
ple, if you issue a SOURCE file_name command to execute statements stored in a file,
file_name must be given on the same line as SOURCE. It may not be entered on the next line.
By default, the short command forms are recognized on any input line, except within quoted
strings. The long command forms aren’t recognized except at the mysql> primary prompt.
For example, CLEAR and \c both clear (cancel) the current command, which is useful if you
change your mind about issuing the statement that you’re currently entering. But CLEAR isn’t
recognized after the first line of a multiple-line statement, so you should use \c instead. To
have mysql recognize the long command names on any input line, invoke it with the
--named-commands option.
04 6329 ch03 3/16/04 4:22 PM Page 43
db_name names the database containing the table to be loaded and input_file names the file
that contains the data to be loaded.
mysqlimport uses the filename to determine the name of the table into which the data should
be loaded. The program does this by stripping off any filename extension (the last period
and anything following it); the result is then used as the table name. For example,
mysqlimport treats a file named City.txt or City.dat as input to be loaded into a table
named City.
04 6329 ch03 3/16/04 4:22 PM Page 44
If you name multiple files on the command line after the database name, mysqlimport issues
a LOAD DATA INFILE statement for each file.
Each table to be loaded by mysqlimport must already exist, and each input file should con-
tain only data values. mysqlimport isn’t intended for processing files that consist of SQL
statements (such files can be created with the mysqldump program). For instructions on pro-
cessing an SQL-format dump file produced by mysqldump that contains SQL statements, see
section 3.4, “Using mysqldump.”
The options part of the mysqlimport command may include any of the standard connection
parameter options, such as --host or --user. You’ll need to supply these options if the
default connection parameters aren’t appropriate. mysqlimport also understands options spe-
cific to its own operation. Invoke mysqlimport with the --help option to see a complete list
of the options that can be used to tell mysqlimport the actions you want it to perform.
By default, input files for mysqlimport are assumed to contain lines terminated by newlines,
with each line containing tab-separated data values. For an input file that’s in a different for-
mat, use the following options to tell mysqlimport how to interpret the file:
n --lines-terminated-by=string
string specifies the character sequence that each input line ends with. The default is \n
(linefeed, also known as newline); other common line terminators are \r (carriage
return) and \r\n (carriage return/linefeed pairs).
n --fields-terminated-by=string
string specifies the delimiter between data values within input lines. The default delim-
iter is \t (tab).
n --fields-enclosed-by=char or --fields-optionally-enclosed-by=char
char indicates a quote character that surrounds data values in the file. By default, values
are assumed not to be quoted. Use this option if values are quoted. A common value for
char is the double quote character (“). If quote characters enclose a data value, they’re
removed before the value is loaded into the table.
n --fields-escaped-by=char
By default, \ within the input is taken as an escape character that signifies a special
sequence. For example, if the \N sequence occurs alone in a field, it’s interpreted as a
NULL value. Use this option to specify a different escape character. To turn escaping off
(no escape character), specify an empty value for char.
The preceding options give you the flexibility to load input files containing data in a variety
of formats. Some examples follow; each one loads an input file named City.txt into the City
table in the world database. Commands that are shown on multiple lines should be entered
on a single line.
The following command loads a file that has lines ending in carriage return/linefeed pairs:
shell> mysqlimport --lines-terminated-by=”\r\n” world City.txt
04 6329 ch03 3/16/04 4:22 PM Page 45
Note that the --lines-terminated-by value is quoted with double quotes. Format option
values often contain special characters, such as backslash, that might have special meaning to
your command interpreter. It might be necessary to quote such characters to tell your com-
mand interpreter to pass them, unchanged, to mysqlimport.
The syntax for specifying a double quote is trickier and depends on which command inter-
preter you use. The following command loads a datafile containing values quoted by double
quote characters:
shell> mysqlimport --fields-terminated-by=’”’ world City.txt
This command should work on most Unix shells, which allow the double quote character to
be quoted within single quotes. This doesn’t work on Windows, where you must specify a
double quote within a double-quoted string by escaping it:
shell> mysqlimport --fields-terminated-by=”\”” world City.txt
The following command loads a file that has data values separated by commas, and lines
ending with carriage returns:
shell> mysqlimport --fields-terminated-by=,
--lines-terminated-by=”\r” world City.txt
Other mysqlimport options provide additional control over datafile loading. The following
list discusses some of those you’re likely to find useful:
n --ignore or --replace
These options tell mysqlimport how to handle input records that contain unique key
values that are already present in the table. Such records result in duplicate-key errors
and cannot be loaded by default. --ignore causes duplicates in the input file to be
ignored. --replace causes existing records in the table to be replaced by duplicates in
the input file.
n --local
By default, a datafile to be loaded into a table is assumed to reside on the server host,
allowing the server to read the file directly. This is very efficient, but requires the user
running mysqlimport to have the FILE privilege (a powerful privilege normally reserved
for administrators). The --local option allows use of a datafile that’s located locally on
the client host where mysqlimport is invoked. With --local, mysqlimport reads the
datafile and sends it over the network to the server. This allows mysqlimport to read any
file on the client host to which the invoker has access, without requiring the invoker to
have the FILE privilege. For the --local option to work, the server must be configured
to allow local files to be transferred to it.
04 6329 ch03 3/16/04 4:22 PM Page 46
The contents of the world.sql file will begin something like this (statements to create
and load the other tables in the database would follow the partial display shown here):
-- MySQL dump 9.10
--
-- Host: localhost Database: world
---------------------------------------------------------
-- Server version 4.0.18-log
--
-- Table structure for table ‘City’
--
--
-- Dumping data for table ‘City’
--
04 6329 ch03 3/16/04 4:22 PM Page 47
The following command names just the City and Country tables after the database
name, so mysqldump dumps just those tables to a file called city_country.sql:
shell> mysqldump world City Country > city_country.sql
n With the --databases (or -B) option, mysqldump interprets any nonoption argument as
a database name and dumps all the tables in each of the named databases. For example,
the following command dumps both the world and test databases into a single file:
shell> mysqldump --databases world test > world_and_test.sql
n With the --all-databases (or -A) option, mysqldump dumps all tables in all databases.
For example, this command writes a backup for all databases to the file alldb.sql:
shell> mysqldump --all-databases > alldb.sql
If you manage a lot of data, alldb.sql will be very large. Be sure that you have suffi-
cient free disk space before issuing such a command.
mysqldump understands the standard connection parameter options, such as --host and
--user.You’ll need to supply these options if the default connection parameters aren’t
appropriate. mysqldump also understands options that provide more specific control over the
dump operation. Invoke mysqldump with the --help option to see a list of available options.
Those options described here are ones you’re likely to find most useful:
n --add-drop-table
Instructs mysqldump to precede the dump output for each table with a DROP TABLE state-
ment that drops the table. This option ensures that when you reload the
dump output, the reload operation removes any existing copy of the table before
re-creating it.
n --all or -a
Instructs mysqldump to produce CREATE TABLE statements that include all the MySQL-
specific options (such as the table type and table comment) with which each table was
created. By default, mysqldump does not include all these options, resulting in dump
files that might be more portable for loading with a DBMS other than MySQL. With
the --all option, tables created during reloading into MySQL will have the same
options as the original tables.
04 6329 ch03 3/16/04 4:22 PM Page 48
n --extended-insert or -e
By default, mysqldump writes each row as a separate INSERT statement. This option pro-
duces multiple-row INSERT statements that add several rows to the table at a time.
Multiple-row statements can be reloaded more efficiently, although they’re less read-
able than single-row statements if you examine the dump output. They’re also less
portable and might not be understood by other database systems.
n --no-create-db or -n
Normally, when you run mysqldump with the --all-databases or --databases option,
the program precedes the dump output for each database with a CREATE DATABASE state-
ment to ensure that the database is created if it doesn’t already exist. The --no-create-
db option causes CREATE DATABASE statements not to be written. Note that their pres-
ence in the file is usually not a problem. They include an IF NOT EXISTS clause, so
they’re ignored when reloading the dump file for any database that does exist.
n --no-create-info or -t
This option suppresses the CREATE TABLE statement that normally precedes the INSERT
statements containing a table’s data. Use this option when you’re interested in dumping
only a table’s data. The option is useful mostly when you plan to reload the data into
tables that already exist.
n --no-data or -d
This option suppresses the INSERT statements containing table data. Use this option
when you’re interested in dumping only the CREATE TABLE statements that describe
table structures. The --no-data option provides an easy way to get a dump file that can
be processed to create empty tables with the same structure as the original tables.
n --opt
This option turns on a set of additional options to make the dump and reload opera-
tions more efficient. Specifically, it’s equivalent to using the --add-drop-table,
--add-locks, --all, --quick, --extended-insert, --lock-tables, and --disable-keys
options together. Note that this option makes the output less portable and less likely to
be understood by other database systems.
n --quick
This option tells mysqldump to write dump output as it reads each row from the server,
which might be useful for large tables. By default, mysqldump reads all rows from a table
into memory before writing the output; for large tables, this requires large amounts of
memory, possibly causing the dump to fail.
mysql can read from a pipe, so you can combine the use of mysqldump and mysql into a single
command. The preceding example can thus be written as one command:
shell> mysqldump --opt world Country | mysql test
This technique also can be used to copy databases or tables over the network to another
server. For example, the following command uses a pipe to copy the Country table from the
world database on the local host to the world database on the remote host other.host.com:
need to make sure that the server doesn’t have the tables open and isn’t using them at the
same time. It’s possible to get incorrect results or even to cause table damage if table files are
used by myisamchk and the server simultaneously. The most certain way to avoid conflict is
to bring the server down while running myisamchk. It’s also possible to lock the tables while
checking or repairing them with myisamchk, but the procedure is not described here. You can
find the details in the MySQL Reference Manual.
The rest of this section describes how to use mysqlcheck and myisamchk.
mysqlcheck has three general modes of operation, depending on how it is invoked:
n By default, mysqlcheck interprets its first nonoption argument as a database name and
checks all the tables in that database. If any other arguments follow the database name,
mysqlcheck treats them as table names and checks just those tables. For example, the
first of the following commands checks all the tables in the world database; the second
checks just the City and Country tables in that database:
shell> mysqlcheck world
shell> mysqlcheck world City Country
n With the --databases (or -B) option, mysqlcheck interprets its nonoption arguments as
database names and checks all the tables in each of the named databases. The following
command checks the tables in both the world and test databases:
shell> mysqlcheck --databases world test
n With the --all-databases (or -A) option, mysqlcheck checks all tables in all databases:
shell> mysqlcheck --all-databases
The procedure for using myisamchk is quite different, due to the need to avoid using tables at
the same time the server might be accessing them. Use myisamchk as follows:
1. Stop the server so that it cannot access the tables while you’re working with them.
2. From a command prompt, change location into the database directory where the tables
are located. This will be the subdirectory of the server’s data directory that has the same
name as the database containing the tables you would like to check. (The reason for
changing location is to make it easier to refer to the table files. You can skip this step
if you like, but you’ll have to specify to myisamchk the directory where the tables are
located.)
3. Invoke myisamchk with options indicating the operation you want performed, followed
by arguments that name the tables on which myisamchk should operate. Each of these
arguments can be either a table name or the name of the table’s index file. An index file-
name is the same as the table name, plus an .MYI suffix.
The default myisamchk operation is to check tables. If that’s what you want to do, no options
are necessary and you need only name the table or tables to be checked. For example, to
check a table named City, either of these commands will do:
04 6329 ch03 3/16/04 4:22 PM Page 51
mysqlcheck and myisamchk both take many options to control the type of table maintenance
operation performed. The following list summarizes some of the more commonly used
options. For the most part, the list contains options that are understood by both programs.
Where this isn’t the case, it’s noted in the relevant option description.
n --analyze or -a
Analyze the distribution of key values in the table. This can improve performance of
queries by speeding up index-based lookups.
n --auto-repair (mysqlcheck only)
Repair tables automatically if a check operation discovers problems.
n --check or -c
Check tables for problems. This is the default action if no other operation is specified.
n --check-only-changed or -C
Skip table checking except for tables that have been changed since they were last
checked or tables that haven’t been properly closed. The latter condition might occur if
the server crashes while a table is open.
n --fast or -F
Skip table checking except for tables that haven’t been properly closed.
n --extended (for mysqlcheck), --extend-check (for myisamchk), or -e (for both programs)
Run an extended table check. For mysqlcheck, when this option is given in conjunction
with a repair option, a more thorough repair is performed than when the repair option
is given alone. That is, the repair operation performed by mysqlcheck --repair
--extended is more thorough than the operation performed by mysqlcheck --repair.
n --medium-check or -m
Run a medium table check.
n --quick or -q
For mysqlcheck, --quick without a repair option causes only the index file to be
checked, leaving the datafile alone. For both programs, --quick in conjunction with a
repair option causes the program to repair only the index file, leaving the datafile alone.
n --repair (for mysqlcheck), --recover (for myisamchk), or -r (for both programs)
Run a table repair operation.
04 6329 ch03 3/16/04 4:22 PM Page 52
The MySQLCC (MySQL Control Center) program provides a graphical interface to the
MySQL server. Precompiled binaries are currently available for Windows and Linux.
MySQLCC can also be compiled from source.
MySQLCC is downloaded separately from MySQL Server and was at Version 0.9.4 (Beta) at the
beginning of 2004.
The following list describes some of the features offered by MySQLCC:
n Interactive query entry and editing, including syntax highlighting and tab-completion.
Syntax highlighting helps you see and understand the structure of queries more readily.
With tab-completion, you can enter part of a keyword or identifier and complete it
using the Tab key.
n A status window that provides easy access to the server’s variables and status indicators.
The window displays the output from the SHOW VARIABLES and SHOW STATUS statements.
04 6329 ch03 3/16/04 4:22 PM Page 53
3.8 Exercises 53
n Capabilities for administering the server. For example, if you connect to the server
using an account that has the appropriate privileges, you can flush logs, kill client con-
nections, or tell the server to shut down.
n Capabilities for managing and administering user accounts.
3.8 Exercises
Question 1:
If you connect to a local server on a Unix machine using the hostname localhost, will the
connection be made using TCP/IP or a Unix socket file? How will the connection be made
if you use the local host’s actual name?
04 6329 ch03 3/16/04 4:22 PM Page 54
Question 2:
Which connection parameters identify you to the MySQL server?
Question 3:
You want to execute a number of prewritten queries using the MySQL server running on
the host db.myexample.com. Your mysql username is juan and you want to be prompted for
your password. The prewritten queries are stored in the file /tmp/queries.sql and you want
world to be the default database. What command do you issue?
Question 4:
Having connected to a server with the mysql client program, you want to run a query and
display its output vertically. What statement terminator do you use to end the query?
Question 5:
Using mysql, you’re about to enter a record into a table that has only one column. You’ve
typed INSERT INTO tbl VALUES (‘teststring and pressed Enter. Now the prompt looks like
this: ‘>. What do you enter to perform the following operations?
a. Send a valid query to the server
b. Cancel the query
Question 6:
In an interactive session using mysql, you want to insert records into a table in the test data-
base using a text file containing INSERT statements. The file is named tbl_import.sql and
resides in /tmp. What command do you use to process the file in the following ways?
a. Within the mysql session
b. From the shell of your operating system
Question 7:
You’re in the process of entering a long SQL statement in mysql and you decide not to send
it to the server. What do you type to cancel the statement?
Question 8:
How do you back up the tables City and Country from the world database into the file
/tmp/world_backup.sqlusing a single mysqldump command?
Question 9:
How do you back up the databases db1 and db2 into the file /tmp/db1_db2_backup.sql with a
single mysqldump command that ensures existing tables will be overwritten when you restore
them?
04 6329 ch03 3/16/04 4:22 PM Page 55
3.8 Exercises 55
Question 10:
What are the advantages and disadvantages of the multiple-row INSERT statements mysqldump
can produce?
Question 11:
You want to produce a backup of the test database into the file /backups/structure.sql
using mysqldump. However, the purpose of the backup file is to create an empty copy of each
table on another server. What command do you issue?
Question 12:
How do you restore a backup of tables in the test database from a backup file called
/backups/back.sql? What options can you use with mysqldump to ensure existing tables will
be overwritten when the tables are restored? If you don’t use this mysqldump option, what
option can you use when you restore the tables to ensure that the restore operation doesn’t
stop when it finds that a table already exists in the database?
Question 13:
Describe the main difference between mysqlcheck and myisamchk.
Question 14:
For which table types can you use mysqlcheck?
Question 15:
For which table types can you use myisamchk?
Question 16:
In addition to providing access to your database, MySQLCC serves as a graphical tool for server
administration.
a. What administrative actions does MySQLCC enable you to perform?
b. What types of information about the server does MySQLCC provide?
c. Besides the server, what else can you administer with MySQLCC?
Answers to Exercises
Answer 1:
1. A Unix socket file will be used.
2. When using the actual hostname, TCP/IP will be used.
Answer 2:
--user (or -u) and --password (or -p).
04 6329 ch03 3/16/04 4:22 PM Page 56
Answer 3:
shell> mysql -h db.example.com -p -u juan world < /tmp/queries.sql
Answer 4:
Use the \G sequence to display query output in vertical format.
Answer 5:
a. One possibility is ‘);
b. Another is to use the clear-query sequence: ‘\c
The ‘> prompt indicates that you began a single-quoted string but haven’t finished it. Thus,
you must enter the terminating single quote to finish the string regardless of whether you
then want to enter the rest of the query or enter the cancel-query command.
Answer 6:
a. To process the file within the mysql session, use the SOURCE command:
mysql> SOURCE /tmp/tbl_import.sql;
(Note that the semicolon is optional for the SOURCE command.) If test isn’t the default
database, you must first issue a USE test statement before processing the file.
b. To process the file from the shell of the operating system, invoke mysql and direct it to
read from the file:
shell> mysql test < /tmp/tbl_import.sql
Answer 7:
To cancel a statement that you are entering, use the \c sequence.
Answer 8:
shell> mysqldump world City Country > /tmp/world_backup.sql
3.8 Exercises 57
Answer 11:
shell> mysqldump --no-data test > /backups/structure.sql
To restore backups made without the --add-drop-table option, you can use the mysql
--force, which will continue processing queries in batch mode even if errors occur.
Answer 13:
The main difference between mysqlcheck and myisamchk lies in how they access tables:
n mysqlcheck is a client program; it determines which options were given on the com-
mand line, and then sends appropriate SQL statements to the MySQL server to per-
form the requested operation.
n myisamchk is not a client program for the server. It performs operations on tables by
accessing the table files directly.
Answer 14:
mysqlcheck can perform operations on MyISAM, InnoDB, and BDB tables.
Answer 15:
myisamchk works only for MyISAM tables.
Answer 16:
a. MySQLCC enables you to kill client connections, issue flush commands, and shut down the
server.
b. MySQLCC has a server information window that provides single-click access to the same
system and status variables that you get when issuing SHOW VARIABLES and SHOW STATUS
statements manually.
c. MySQLCC also enables you to administer user accounts.