Chapter 4. MySQL Programs
Table of Contents
- 4.1. Overview of MySQL Programs
- 4.2. Using MySQL Programs
- 4.3. MySQL Server and Server-Startup Programs
- 4.4. MySQL Installation-Related Programs
- 4.4.1. comp_err — Compile MySQL Error Message File
- 4.4.2. make_win_src_distribution — Create Source Distribution for Windows
- 4.4.3. mysql_create_system_tables — Generate Statements to Initialize MySQL System Tables
- 4.4.4. mysqlbug — Generate Bug Report
- 4.4.5. mysql_fix_privilege_tables — Upgrade MySQL System Tables
- 4.4.6. mysql_install_db — Initialize MySQL Data Directory
- 4.4.7. mysql_secure_installation — Improve MySQL Installation Security
- 4.4.8. mysql_tzinfo_to_sql — Load the Time Zone Tables
- 4.5. MySQL Client Programs
- 4.5.1. mysql — The MySQL Command-Line Tool
- 4.5.2. mysqladmin — Client for Administering a MySQL Server
- 4.5.3. mysqlcheck — A Table Maintenance Program
- 4.5.4. mysqldump — A Database Backup Program
- 4.5.5. mysqlimport — A Data Import Program
- 4.5.6. mysqlshow — Display Database, Table, and Column Information
- 4.6. MySQL Administrative and Utility Programs
- 4.6.1. myisam_ftdump — Display Full-Text Index information
- 4.6.2. myisamchk — MyISAM Table-Maintenance Utility
- 4.6.3. myisamlog — Display MyISAM Log File Contents
- 4.6.4. myisampack — Generate Compressed, Read-Only MyISAM Tables
- 4.6.5. mysqlaccess — Client for Checking Access Privileges
- 4.6.6. mysqlbinlog — Utility for Processing Binary Log Files
- 4.6.7. mysqldumpslow — Summarize Slow Query Log Files
- 4.6.8. mysqlhotcopy — A Database Backup Program
- 4.6.9. mysqlmanagerc — Internal Test-Suite Program
- 4.6.10. mysqlmanager-pwgen — Internal Test-Suite Program
- 4.6.11. mysql_convert_table_format — Convert Tables to Use a Given Storage Engine
- 4.6.12. mysql_explain_log — Use EXPLAIN on Statements in Query Log
- 4.6.13. mysql_find_rows — Extract SQL Statements from Files
- 4.6.14. mysql_fix_extensions — Normalize Table File Name Extensions
- 4.6.15. mysql_setpermission — Interactively Set Permissions in Grant Tables
- 4.6.16. mysql_tableinfo — Generate Database Metadata
- 4.6.17. mysql_waitpid — Kill Process and Wait for Its Termination
- 4.6.18. mysql_zap — Kill Processes That Match a Pattern
- 4.7. MySQL Program Development Utilities
- 4.8. Miscellaneous Programs
This chapter provides a brief overview of the command-line programs provided by MySQL AB. It also discusses the general syntax for specifying options when you run these programs. Most programs have options that are specific to their own operation, but the option syntax is similar for all of them. Finally, the chapter provides more detailed descriptions of individual programs, including which options they recognize.
There are many different programs in a MySQL installation. This section provides a brief overview of them. Later sections provide a more detailed description of each one, with the exception of MySQL Cluster programs. Each program's description indicates its invocation syntax and the options that it supports. Chapter 15, MySQL Cluster, describes programs specific to MySQL Cluster.
Most MySQL distributions include all of these programs, except for those programs that are platform-specific. (For example, the server startup scripts are not used on Windows.) The exception is that RPM distributions are more specialized. There is one RPM for the server, another for client programs, and so forth. If you appear to be missing one or more programs, see Chapter 2, Installing and Upgrading MySQL, for information on types of distributions and what they contain. It may be that you have a distribution that does not include all programs and you need to install an additional package.
Each MySQL program takes many different options. Most programs
provide a --help option that you can use to get a
description of the program's different options. For example, try
mysql --help.
You can override default option values for MySQL programs by specifying options on the command line or in an option file. See Section 4.2, “Using MySQL Programs”, for general information on invoking programs and specifying program options.
The MySQL server, mysqld, is the main program that does most of the work in a MySQL installation. The server is accompanied by several related scripts that assist you in starting and stopping the server:
The SQL daemon (that is, the MySQL server). To use client programs, mysqld must be running, because clients gain access to databases by connecting to the server. See Section 4.3.1, “mysqld — The MySQL Server”.
A version of the server that includes additional features. See Section 5.2, “The mysqld-max Extended MySQL Server”.
A server startup script. mysqld_safe attempts to start mysqld-max if it exists, and mysqld otherwise. See Section 4.3.2, “mysqld_safe — MySQL Server Startup Script”.
A server startup script. This script is used on systems that use System V-style run directories containing scripts that start system services for particular run levels. It invokes mysqld_safe to start the MySQL server. See Section 4.3.3, “mysql.server — MySQL Server Startup Script”.
A server startup script that can start or stop multiple servers installed on the system. See Section 4.3.4, “mysqld_multi — Manage Multiple MySQL Servers”.
There are several programs that perform setup operations during MySQL installation or upgrading:
This program is used during the MySQL build/installation process. It compiles error message files from the error source files. See Section 4.4.1, “comp_err — Compile MySQL Error Message File”.
This program makes a binary release of a compiled MySQL. This could be sent by FTP to
/pub/mysql/upload/onftp.mysql.comfor the convenience of other MySQL users.This script is invoked by mysql_install_db to generate the SQL statements required to initialize the grant tables with default privileges. See Section 4.4.3, “mysql_create_system_tables — Generate Statements to Initialize MySQL System Tables”.
This program is used after a MySQL upgrade operation. It updates the grant tables with any changes that have been made in newer versions of MySQL. See Section 4.4.5, “mysql_fix_privilege_tables — Upgrade MySQL System Tables”.
This script creates the MySQL database and initializes the grant tables with default privileges. It is usually executed only once, when first installing MySQL on a system. See Section 4.4.6, “mysql_install_db — Initialize MySQL Data Directory”, Section 2.10.2, “Unix Post-Installation Procedures”, and Section 4.4.6, “mysql_install_db — Initialize MySQL Data Directory”.
This program enables you to improve the security of your MySQL installation. SQL. See Section 4.4.7, “mysql_secure_installation — Improve MySQL Installation Security”.
This program loads the time zone tables in the
mysqldatabase using the contents of the host system zoneinfo database (the set of files describing time zones). SQL. See Section 4.4.8, “mysql_tzinfo_to_sql — Load the Time Zone Tables”.This program is used on Unix or Unix-like systems to create a MySQL source distribution that can be compiled on Windows. See Section 2.9.6.2, “Creating a Windows Source Package from the Latest Development Source”, and Section 4.4.2, “make_win_src_distribution — Create Source Distribution for Windows”.
MySQL client programs:
The command-line tool for interactively entering SQL statements or executing them from a file in batch mode. See Section 4.5.1, “mysql — The MySQL Command-Line Tool”.
A client that performs administrative operations, such as creating or dropping databases, reloading the grant tables, flushing tables to disk, and reopening log files. mysqladmin can also be used to retrieve version, process, and status information from the server. See Section 4.5.2, “mysqladmin — Client for Administering a MySQL Server”.
A table-maintenance client that checks, repairs, analyzes, and optimizes tables. See Section 4.5.3, “mysqlcheck — A Table Maintenance Program”.
A client that dumps a MySQL database into a file as SQL, text, or XML. See Section 4.5.4, “mysqldump — A Database Backup Program”.
A client that imports text files into their respective tables using
LOAD DATA INFILE. See Section 4.5.5, “mysqlimport — A Data Import Program”.A client that displays information about databases, tables, columns, and indexes. See Section 4.5.6, “mysqlshow — Display Database, Table, and Column Information”.
MySQL administrative and utility programs:
A utility that displays information about full-text indexes in
MyISAMtables. See Section 4.6.1, “myisam_ftdump — Display Full-Text Index information”.myisamchk, isamchk
A utility to describe, check, optimize, and repair
MyISAMtables. isamchk is a similar program forISAMtables. See Section 4.6.2, “myisamchk — MyISAM Table-Maintenance Utility”.myisamlog, isamlog
Utilities that process the contents of a
MyISAMorISAMlog file. See Section 4.6.3, “myisamlog — Display MyISAM Log File Contents”.myisampack, pack_isam
Utilities that compress
MyISAMorISAMtables to produce smaller read-only tables. See Section 4.6.4, “myisampack — Generate Compressed, Read-Only MyISAM Tables”.A script that checks the access privileges for a host name, user name, and database combination. See Section 4.6.5, “mysqlaccess — Client for Checking Access Privileges”.
A utility for reading statements from a binary log. The log of executed statements contained in the binary log files can be used to help recover from a crash. See Section 4.6.6, “mysqlbinlog — Utility for Processing Binary Log Files”.
A utility to read and summarize the contents of a slow query log. See Section 4.6.7, “mysqldumpslow — Summarize Slow Query Log Files”.
A utility that quickly makes backups of
MyISAMorISAMtables while the server is running. See Section 4.6.8, “mysqlhotcopy — A Database Backup Program”.A utility that converts tables in a database to use a given storage engine. See Section 4.6.11, “mysql_convert_table_format — Convert Tables to Use a Given Storage Engine”.
A utility that analyzes queries in the MySQL query log using
EXPLAINSee Section 4.6.12, “mysql_explain_log — Use EXPLAIN on Statements in Query Log”.A utility that reads files containing SQL statements (such as update logs) and extracts statements that match a given regular expression. See Section 4.6.13, “mysql_find_rows — Extract SQL Statements from Files”.
A utility that converts the extensions for
MyISAM(orISAM) table files to lowercase. This can be useful after transferring the files from a system with case-insensitive file names to a system with case-sensitive file names. See Section 4.6.14, “mysql_fix_extensions — Normalize Table File Name Extensions”.A utility for interactively setting permissions in the MySQL grant tables. See Section 4.6.15, “mysql_setpermission — Interactively Set Permissions in Grant Tables”.
A utility that generates database metadata. Section 4.6.16, “mysql_tableinfo — Generate Database Metadata”.
A utility that kills the process with a given process ID. See Section 4.6.17, “mysql_waitpid — Kill Process and Wait for Its Termination”.
A utility that kills processes that match a pattern. See Section 4.6.18, “mysql_zap — Kill Processes That Match a Pattern”.
MySQL program-development utilities:
A shell script that converts
mSQLprograms to MySQL. It doesn't handle every case, but it gives a good start when converting. See Section 4.7.1, “msql2mysql — Convert mSQL Programs for Use with MySQL”.A shell script that produces the option values needed when compiling MySQL programs. See Section 4.7.2, “mysql_config — Get Compile Options for Compiling Clients”.
A utility that shows which options are present in option groups of option files. See Section 4.7.3, “my_print_defaults — Display Options from Option Files”.
A utility program that resolves a numeric stack trace dump to symbols. See Section 4.7.4, “resolve_stack_dump — Resolve Numeric Stack Trace Dump to Symbols”.
Miscellaneous utilities:
A utility that displays the meaning of system or MySQL error codes. See Section 4.8.1, “perror — Explain Error Codes”.
A utility program that performs string replacement in the input text. See Section 4.8.2, “replace — A String-Replacement Utility”.
A utility program that resolves a host name to an IP address or vice versa. See Section 4.8.3, “resolveip — Resolve Host name to IP Address or Vice Versa”.
MySQL AB also provides several GUI tools for administering and otherwise working with MySQL Server:
MySQL Administrator: This tool is used for administering MySQL servers, databases, tables, and user accounts.
MySQL Query Browser: This graphical tool is provided by MySQL AB for creating, executing, and optimizing queries on MySQL databases.
MySQL Migration Toolkit: This tool helps you migrate schemas and data from other relational database management systems for use with MySQL.
These GUI programs are available at http://dev.mysql.com/downloads/. Each has its own manual that you can access at http://dev.mysql.com/doc/.
MySQL client programs that communicate with the server using the MySQL client/server library use the following environment variables.
MYSQL_UNIX_PORT | The default Unix socket file; used for connections to
localhost |
MYSQL_TCP_PORT | The default port number; used for TCP/IP connections |
MYSQL_PWD | The default password |
MYSQL_DEBUG | Debug trace options when debugging |
TMPDIR | The directory where temporary tables and files are created |
For a full list of environment variables used by MySQL programs, see Section 2.13, “Environment Variables”.
Use of MYSQL_PWD is insecure. See
Section 5.6.6.2, “End-User Guidelines for Password Security”.
To invoke a MySQL program from the command line (that is, from
your shell or command prompt), enter the program name followed by
any options or other arguments needed to instruct the program what
you want it to do. The following commands show some sample program
invocations. “shell>”
represents the prompt for your command interpreter; it is not part
of what you type. The particular prompt you see depends on your
command interpreter. Typical prompts are $ for
sh or bash,
% for csh or
tcsh, and C:\> for the
Windows command.com or
cmd.exe command interpreters.
shell>mysql --user=root testshell>mysqladmin extended-status variablesshell>mysqlshow --helpshell>mysqldump -u root personnel
Arguments that begin with a single or double dash
(“-”,
“--”) specify program options.
Options typically indicate the type of connection a program should
make to the server or affect its operational mode. Option syntax
is described in Section 4.2.3, “Specifying Program Options”.
Nonoption arguments (arguments with no leading dash) provide
additional information to the program. For example, the
mysql program interprets the first nonoption
argument as a database name, so the command mysql
--user=root test indicates that you want to use the
test database.
Later sections that describe individual programs indicate which options a program supports and describe the meaning of any additional nonoption arguments.
Some options are common to a number of programs. The most
frequently used of these are the
--host (or -h),
--user (or -u),
and --password (or
-p) options that specify connection parameters.
They indicate the host where the MySQL server is running, and the
user name and password of your MySQL account. All MySQL client
programs understand these options; they allow you to specify which
server to connect to and the account to use on that server. Other
connection options are --port (or
-P) to specify a TCP/IP port number and
--socket (or -S)
to specify a Unix socket file on Unix (or named pipe name on
Windows). For more information on options that specify connection
options, see Section 4.2.2, “Connecting to the MySQL Server”.
You may find it necessary to invoke MySQL programs using the path
name to the bin directory in which they are
installed. This is likely to be the case if you get a
“program not found” error whenever you attempt to run
a MySQL program from any directory other than the
bin directory. To make it more convenient to
use MySQL, you can add the path name of the
bin directory to your PATH
environment variable setting. That enables you to run a program by
typing only its name, not its entire path name. For example, if
mysql is installed in
/usr/local/mysql/bin, you can run the program
by invoking it as mysql, and it is not
necessary to invoke it as
/usr/local/mysql/bin/mysql.
Consult the documentation for your command interpreter for
instructions on setting your PATH variable. The
syntax for setting environment variables is interpreter-specific.
(Some information is given in
Section 4.2.4, “Setting Environment Variables”.) After modifying
your PATH setting, open a new console window on
Windows or log in again on Unix so that the setting goes into
effect.
For a client program to be able to connect to the MySQL server, it must use the proper connection parameters, such as the name of the host where the server is running and the user name and password of your MySQL account. Each connection parameter has a default value, but you can override them as necessary using program options specified either on the command line or in an option file.
The examples here use the mysql client program, but the principles apply to other clients such as mysqldump, mysqladmin, or mysqlshow.
This command invokes mysql without specifying any connection parameters explicitly:
shell> mysql
Because there are no parameter options, the default values apply:
The default host name is
localhost. On Unix, this has a special meaning, as described later.The default user name is
ODBCon Windows or your Unix login name on Unix.No password is sent if neither
-pnor--passwordis given.For mysql, the first nonoption argument is taken as the name of the default database. If there is no such option, mysql does not select a default database.
To specify the host name and user name explicitly, as well as a password, supply appropriate options on the command line:
shell>mysql --host=localhost --user=myname --password=mypass mydbshell>mysql -h localhost -u myname -pmypass mydb
For password options, the password value is optional:
If you use a
-por--passwordoption and specify the password value, there must be no space between-por--password=and the password following it.If you use a
-por--passwordoption but do not specify the password value, the client program prompts you to enter the password. The password is not displayed as you enter it. This is more secure than giving the password on the command line. Other users on your system may be able to see a password specified on the command line by executing a command such as ps auxw. See Section 5.6.6.2, “End-User Guidelines for Password Security”.
As just mentioned, including the password value on the command
line can be a security risk. To avoid this problem, specify the
--password or -p option without
any following password value:
shell>mysql --host=localhost --user=myname --password mydbshell>mysql -h localhost -u myname -p mydb
When the password option has no password value, the client program
prints a prompt and waits for you to enter the password. (In these
examples, mydb is not
interpreted as a password because it is separated from the
preceding password option by a space.)
On some systems, the library routine that MySQL uses to prompt for a password automatically limits the password to eight characters. That is a problem with the system library, not with MySQL. Internally, MySQL does not have any limit for the length of the password. To work around the problem, change your MySQL password to a value that is eight or fewer characters long, or put your password in an option file.
On Unix, MySQL programs treat the host name
localhost specially, in a way that is likely
different from what you expect compared to other network-based
programs. For connections to localhost, MySQL
programs attempt to connect to the local server by using a Unix
socket file. This occurs even if a
--port or -P
option is given to specify a port number. To ensure that the
client makes a TCP/IP connection to the local server, use
--host or -h to
specify a host name value of 127.0.0.1, or the
IP address or name of the local server. You can also specify the
connection protocol explicitly, even for
localhost, by using the
--protocol=TCP option. For
example:
shell>mysql --host=127.0.0.1shell>mysql --protocol=TCP
The --protocol option enables you
to establish a particular type of connection even when the other
options would normally default to some other protocol.
On Windows, you can force a MySQL client to use a named-pipe
connection by specifying the
--pipe or
--protocol=PIPE option, or by
specifying . (period) as the host name. If
named-pipe connections are not enabled, an error occurs. Use the
--socket option to specify the
name of the pipe if you do not want to use the default pipe name.
Connections to remote servers always use TCP/IP. This command
connects to the server running on
remote.example.com using the default port
number (3306):
shell> mysql --host=remote.example.com
To specify a port number explicitly, use the
--port or -P
option:
shell> mysql --host=remote.example.com --port=13306
You can specify a port number for connections to a local server,
too. However, as indicated previously, connections to
localhost on Unix will use a socket file by
default. You will need to force a TCP/IP connection as already
described or any option that specifies a port number will be
ignored.
For this command, the program uses a socket file on Unix and the
--port option is ignored:
shell> mysql --port=13306 --host=localhost
To cause the port number to be used, invoke the program in either of these ways:
shell>mysql --port=13306 --host=127.0.0.1shell>mysql --port=13306 --protocol=TCP
The following list summarizes the options that can be used to control how client programs connect to the server:
--host=,host_name-hhost_nameThe host where the server is running. The default value is
localhost.--password[=,pass_val]-p[pass_val]The password of the MySQL account. As described earlier, the password value is optional, but if given, there must be no space between
-por--password=and the password following it. The default is to send no password.--pipe,-WOn Windows, connect to the server via a named pipe. This option applies for connections to a local server only. The server must have been started with the
--enable-named-pipeoption to enable named-pipe connections.--port=,port_num-Pport_numThe port number to use for the connection, for connections made via TCP/IP. The default port number is 3306.
--protocol={TCP|SOCKET|PIPE|MEMORY}This option explicitly specifies a protocol to use for connecting to the server. It is useful when the other connection parameters normally would cause a protocol to be used other than the one you want. For example, connections on Unix to
localhostare made via a Unix socket file by default:shell>
mysql --host=localhostTo force a TCP/IP connection to be used instead, specify a
--protocoloption:shell>
mysql --host=localhost --protocol=TCPThe following table shows the allowable
--protocoloption values and indicates the platforms on which each value may be used. The values are not case sensitive.--protocolValueConnection Protocol Allowable Operating Systems TCPTCP/IP connection to local or remote server All SOCKETUnix socket file connection to local server Unix only PIPENamed-pipe connection to local server Windows only MEMORYShared-memory connection to local server Windows only The
--protocoloption was added in MySQL 4.1.--shared-memory-base-name=nameOn Windows, the shared-memory name to use, for connections made via shared memory to a local server. The default value is
MYSQL. The shared-memory name is case sensitive.The server must be started with the
--shared-memoryoption to enable shared-memory connections.--socket=,file_name-Sfile_nameOn Unix, the name of the Unix socket file to use, for connections made via a named pipe to a local server. The default Unix socket file name is
/tmp/mysql.sock.On Windows, the name of the named pipe to use, for connections to a local server. The default Windows pipe name is
MySQL. The pipe name is not case sensitive.The server must be started with the
--enable-named-pipeoption to enable named-pipe connections.Options that begin with
--sslare used for establishing a secure connection to the server via SSL, if the server is configured with SSL support. For details, see Section 5.6.7.3, “SSL Command Options”.--user=,user_name-uuser_nameThe user name of the MySQL account you want to use. The default user name is
ODBCon Windows or your Unix login name on Unix.
It is possible to specify different default values to be used when you make a connection so that you need not enter them on the command line each time you invoke a client program. This can be done in a couple of ways:
You can specify connection parameters in the
[client]section of an option file. The relevant section of the file might look like this:[client] host=
host_nameuser=user_namepassword=your_passSection 4.2.3.3, “Using Option Files”, discusses option files further.
You can specify some connection parameters using environment variables. The host can be specified for mysql using
MYSQL_HOST. The MySQL user name can be specified usingUSER(this is for Windows and NetWare only). The password can be specified usingMYSQL_PWD, although this is insecure; see Section 5.6.6.2, “End-User Guidelines for Password Security”. For a list of variables, see Section 2.13, “Environment Variables”.
There are several ways to specify options for MySQL programs:
List the options on the command line following the program name. This is most common for options that apply to a specific invocation of the program.
List the options in an option file that the program reads when it starts. This is common for options that you want the program to use each time it runs.
List the options in environment variables (see Section 4.2.4, “Setting Environment Variables”). This method is useful for options that you want to apply each time the program runs. In practice, option files are used more commonly for this purpose, but Section 5.7.2, “Running Multiple Servers on Unix”, discusses one situation in which environment variables can be very helpful. It describes a handy technique that uses such variables to specify the TCP/IP port number and Unix socket file for the server and for client programs.
MySQL programs determine which options are given first by examining environment variables, then by reading option files, and then by checking the command line. This means that environment variables have the lowest precedence and command-line options the highest.
Because options are processed in order, if an option is specified
multiple times, the last occurrence takes precedence. The
following command causes mysql to connect to
the server running on localhost:
shell> mysql -h example.com -h localhost
If conflicting or related options are given, later options take precedence over earlier options. The following command runs mysql in “no column names” mode:
shell> mysql --column-names --skip-column-names
An option can be specified by writing it in full or as any
unambiguous prefix. For example, the
--compress option can be given
to mysqldump as --compr, but
not as --comp because the latter is ambiguous:
shell> mysqldump --comp
mysqldump: ambiguous option '--comp' (compatible, compress)
Be aware that the use of option prefixes can cause problems in the event that new options are implemented for a program. A prefix that is unambiguous now might become ambiguous in the future.
You can take advantage of the way that MySQL programs process options by specifying default values for a program's options in an option file. That enables you to avoid typing them each time you run the program, but also allows you to override the defaults if necessary by using command-line options.
Program options specified on the command line follow these rules:
Options are given after the command name.
An option argument begins with one dash or two dashes, depending on whether it is a short form or long form of the option name. Many options have both short and long forms. For example,
-?and--helpare the short and long forms of the option that instructs a MySQL program to display its help message.Option names are case sensitive.
-vand-Vare both legal and have different meanings. (They are the corresponding short forms of the--verboseand--versionoptions.)Some options take a value following the option name. For example,
-h localhostor--host=localhostindicate the MySQL server host to a client program. The option value tells the program the name of the host where the MySQL server is running.For a long option that takes a value, separate the option name and the value by an “
=” sign. For a short option that takes a value, the option value can immediately follow the option letter, or there can be a space between:-hlocalhostand-h localhostare equivalent. An exception to this rule is the option for specifying your MySQL password. This option can be given in long form as--password=or aspass_val--password. In the latter case (with no password value given), the program prompts you for the password. The password option also may be given in short form as-por aspass_val-p. However, for the short form, if the password value is given, it must follow the option letter with no intervening space. The reason for this is that if a space follows the option letter, the program has no way to tell whether a following argument is supposed to be the password value or some other kind of argument. Consequently, the following two commands have two completely different meanings:shell>
mysql -ptestshell>mysql -p testThe first command instructs mysql to use a password value of
test, but specifies no default database. The second instructs mysql to prompt for the password value and to usetestas the default database.Within option names, dash (“
-”) and underscore (“_”) may be used interchangeably. For example,--skip-grant-tablesand--skip_grant_tablesare equivalent. (However, the leading dashes cannot be given as underscores.)
Another option that may occasionally be useful with
mysql is the
--execute or -e
option, which can be used to pass SQL statements to the server.
When this option is used, mysql executes the
statements and exits. The statements must be enclosed by
quotation marks. For example, you can use the following command
to obtain a list of user accounts:
shell>mysql -u root -p --execute="SELECT User, Host FROM user" mysqlEnter password:******+------+-----------+ | User | Host | +------+-----------+ | | gigan | | root | gigan | | | localhost | | jon | localhost | | root | localhost | +------+-----------+ shell>
Note that the long form
(--execute) is followed by an
equals sign (=).
If you wish to use quoted values within a statement, you will either need to escape the inner quotes, or use a different type of quotes within the statement from those used to quote the statement itself. The capabilities of your command processor dictate your choices for whether you can use single or double quotation marks and the syntax for escaping quote characters. For example, if your command processor supports quoting with single or double quotes, you can double quotes around the statement, and single quotes for any quoted values within the statement.
In the preceding example, the name of the
mysql database was passed as a separate
argument. However, the same statement could have been executed
using this command, which specifies no default database:
mysql> mysql -u root -p --execute="SELECT User, Host FROM mysql.user"
Multiple SQL statements may be passed on the command line, separated by semicolons:
shell>mysql -u root -p -e "SELECT VERSION();SELECT NOW()"Enter password:******+------------+ | VERSION() | +------------+ | 4.1.17-log | +------------+ +---------------------+ | NOW() | +---------------------+ | 2006-01-05 21:19:04 | +---------------------+
The --execute or -e option may
also be used to pass commands in an analogous fashion to the
ndb_mgm management client for MySQL Cluster.
See Section 15.2.6, “Safe Shutdown and Restart of MySQL Cluster”, for
an example.
MySQL 4.0.2 introduced some additional flexibility in the way you specify options. SQL 4.0.2. Some of these changes relate to the way you specify options that have “enabled” and “disabled” states, and to the use of options that might be present in one version of MySQL but not another. Those capabilities are discussed in this section.
Some options are “boolean” and control behavior
that can be turned on or off. Some options control behavior that
can be turned on or off. For example, the
mysql client supports a
--column-names option that
determines whether or not to display a row of column names at
the beginning of query results. By default, this option is
enabled. However, you may want to disable it in some instances,
such as when sending the output of mysql into
another program that expects to see only data and not an initial
header line.
To disable column names, you can specify the option using any of these forms:
--disable-column-names --skip-column-names --column-names=0
The --disable and --skip
prefixes and the =0 suffix all have the same
effect: They turn the option off.
The “enabled” form of the option may be specified in any of these ways:
--column-names --enable-column-names --column-names=1
Another change to option processing introduced in MySQL 4.0.2 is
that you can use the --loose prefix for
command-line options. If an option is prefixed by
--loose, a program does not exit with an error
if it does not recognize the option, but instead issues only a
warning:
shell> mysql --loose-no-such-option
mysql: WARNING: unknown option '--no-such-option'
The --loose prefix can be useful when you run
programs from multiple installations of MySQL on the same
machine and list options in an option file, An option that may
not be recognized by all versions of a program can be given
using the --loose prefix (or
loose in an option file). Versions of the
program that recognize the option process it normally, and
versions that do not recognize it issue a warning and ignore it.
This strategy requires that all versions involved be 4.0.2 or
later, because earlier versions know nothing of the
--loose convention.
As of MySQL 4.0.2, mysqld enables a limit to
be placed on how large client programs can set dynamic system
variables. To do this, use a --maximum prefix
with the variable name. For example,
--maximum-query_cache_size=4M prevents any
client from making the query cache size larger than 4MB.
Most MySQL programs can read startup options from option files (also sometimes called configuration files). Option files provide a convenient way to specify commonly used options so that they need not be entered on the command line each time you run a program. Option file capability is available from MySQL 3.22 on. For the MySQL server, MySQL provides a number of preconfigured option files.
To determine whether a program reads option files, invoke it
with the --help option. (For
mysqld, use
--verbose and
--help as of MySQL 4.1.1.) If the
program reads option files, the help message indicates which
files it looks for and which option groups it recognizes.
Note
Option files used with MySQL Cluster programs are covered in Section 15.3, “MySQL Cluster Configuration”.
On Windows, MySQL programs read startup options from the following files.
| File Name | Purpose |
,
| Global options |
C:\my.ini, C:\my.cnf | Global options |
,
| Global options |
defaults-extra-file | The file specified with
--defaults-extra-file=,
if any |
Note
Programs look for option files using both extensions
(.ini, .cnf) in all
locations only as of MySQL 4.0.23 and 4.1.8. Before MySQL
4.0.23 and 4.1.8, programs look in
WINDIR and
INSTALLDIR only for
my.ini, and in C:\
only for my.cnf.
WINDIR represents the location of
your Windows directory. This is commonly
C:\WINDOWS or
C:\WINNT. You can determine its exact
location from the value of the WINDIR
environment variable using the following command:
C:\> echo %WINDIR%
INSTALLDIR represents the MySQL
installation directory. With MySQL 4.1.5 and up, this is
typically
C:\ where
PROGRAMDIR\MySQL\MySQL
4.1 ServerPROGRAMDIR represents the programs
directory (usually Program Files on
English-language versions of Windows), when MySQL
4.1 has been installed using the installation and
configuration wizards. See
Section 2.3.4.14, “The Location of the my.ini File”.
On Unix, MySQL programs read startup options from the following files.
| File Name | Purpose |
/etc/my.cnf | Global options |
DATADIR/my.cnf | Server-specific options |
defaults-extra-file | The file specified with
--defaults-extra-file=,
if any |
~/.my.cnf | User-specific options |
DATADIR represents the path to the
directory in which the server-specific my.cnf
file resides.
Typically, DATADIR is
/usr/local/mysql/data for a binary
installation or /usr/local/var for a source
installation. Note that this is the data directory location that
was specified at configuration time, not the one specified with
the --datadir option when
mysqld starts. Use of
--datadir at runtime has no
effect on where the server looks for option files, because it
looks for them before processing any options.
MySQL looks for option files in the order just described and reads any that exist. If an option file that you want to use does not exist, create it with a plain text editor.
If multiple instances of a given option are found, the last
instance takes precedence. There is one exception: For
mysqld, the first
instance of the --user option is
used as a security precaution, to prevent a user specified in an
option file from being overridden on the command line.
Note
On Unix platforms, MySQL ignores configuration files that are world-writable. This is intentional as a security measure.
Any long option that may be given on the command line when
running a MySQL program can be given in an option file as well.
To get the list of available options for a program, run it with
the --help option.
The syntax for specifying options in an option file is similar
to command-line syntax, except that you omit the leading two
dashes and you specify only one option per line. For example,
--quick and --host=localhost
on the command line should be specified as
quick and host=localhost
on separate lines in an option file. To specify an option of the
form
--loose- in
an option file, write it as
opt_nameloose-.
opt_name
Empty lines in option files are ignored. Nonempty lines can take any of the following forms:
#,comment;commentComment lines start with “
#” or “;”. As of MySQL 4.0.14, a “#” comment can start in the middle of a line as well.[group]groupis the name of the program or group for which you want to set options. After a group line, any option-setting lines apply to the named group until the end of the option file or another group line is given.opt_nameThis is equivalent to
--on the command line.opt_nameopt_name=valueThis is equivalent to
--on the command line. In an option file, you can have spaces around the “opt_name=value=” character, something that is not true on the command line. As of MySQL 4.0.16, you can enclose the value within double quotes or single quotes. This is useful if the value contains a “#” comment character or whitespace.set-variable =var_name=valueSet the program variable
var_nameto the given value. This is equivalent to--set-variable=on the command line. Spaces are allowed around the first “var_name=value=” character but not around the second. This syntax is deprecated as of MySQL 4.0. See Section 4.2.3.4, “Using Options to Set Program Variables”, for more information on setting program variables.
For options that take a numeric value, the value can be given
with a suffix of K, M, or
G (either uppercase or lowercase) to indicate
a multiplier of 1024, 10242 or
10243. For example, the following
command tells mysqladmin to ping the server
1024 times, sleeping 10 seconds between each ping:
mysql> mysqladmin --count=1K --sleep=10 ping
Leading and trailing blanks are automatically deleted from
option names and values. You may use the escape sequences
“\b”,
“\t”,
“\n”,
“\r”,
“\\”, and
“\s” in option values to
represent the backspace, tab, newline, carriage return,
backslash, and space characters.
Because the “\\” escape sequence
represents a single backslash, you must write each
“\” as
“\\”. Alternatively, you can
specify the value using “/”
rather than “\” as the path name
separator.
If an option group name is the same as a program name, options
in the group apply specifically to that program. For example,
the [mysqld] and [mysql]
groups apply to the mysqld server and the
mysql client program, respectively.
The [client] option group is read by all
client programs (but not by
mysqld). This allows you to specify options
that apply to all clients. For example,
[client] is the perfect group to use to
specify the password that you use to connect to the server. (But
make sure that the option file is readable and writable only by
yourself, so that other people cannot find out your password.)
Be sure not to put an option in the [client]
group unless it is recognized by all client
programs that you use. Programs that do not understand the
option quit after displaying an error message if you try to run
them.
Here is a typical global option file:
[client] port=3306 socket=/tmp/mysql.sock [mysqld] port=3306 socket=/tmp/mysql.sock key_buffer_size=16M max_allowed_packet=8M [mysqldump] quick
The preceding option file uses
syntax for the lines that set the
var_name=valuekey_buffer_size and
max_allowed_packet variables.
Prior to MySQL 4.0.2, you must use
set-variable syntax instead (described
earlier in this section).
Here is a typical user option file:
[client] # The following password will be sent to all standard MySQL clients password="my_password" [mysql] no-auto-rehash set-variable = connect_timeout=2 [mysqlhotcopy] interactive-timeout
This option file uses set-variable syntax to
set the connect_timeout
variable. For MySQL 4.0.2 and up, you can also set the variable
using just connect_timeout = 2.
As of MySQL 4.0.14, if you want to create option groups that
should be read only by mysqld servers from a
specific MySQL release series only, you can do this by using
groups with names of [mysqld-4.0],
[mysqld-4.1], and so forth. The following
group indicates that the --new option should be
used only by MySQL servers with 4.0.x version numbers:
[mysqld-4.0] new
Beginning with MySQL 4.1.11, it is possible to use
!include directives in option files to
include other option files and !includedir to
search specific directories for option files. For example, to
include the /home/mydir/myopt.cnf file, use
the following directive:
!include /home/mydir/myopt.cnf
To search the /home/mydir directory and
read option files found there, use this directive:
!includedir /home/mydir
There is no guarantee about the order in which the option files in the directory will be read.
Note
Currently, any files to be found and included using the
!includedir directive on Unix operating
systems must have file names ending in
.cnf. On Windows, this directive checks
for files with the .ini or
.cnf extension.
Write the contents of an included option file like any other
option file. That is, it should contain groups of options, each
preceded by a
[ line that
indicates the program to which the options apply.
group]
While an included file is being processed, only those options in
groups that the current program is looking for are used. Other
groups are ignored. Suppose that a my.cnf
file contains this line:
!include /home/mydir/myopt.cnf
And suppose that /home/mydir/myopt.cnf
looks like this:
[mysqladmin] force [mysqld] key_buffer_size=16M
If my.cnf is processed by
mysqld, only the [mysqld]
group in /home/mydir/myopt.cnf is used. If
the file is processed by mysqladmin, only the
[mysqldamin] group is used. If the file is
processed by any other program, no options in
/home/mydir/myopt.cnf are used.
The !includedir directive is processed
similarly except that all option files in the named directory
are read.
Most MySQL programs that support option files handle the
following options. They affect option-file handling, so they
must be given on the command line and not in an option file.
To work properly, each of these options must immediately
follow the command name, with the exception that
--print-defaults may be used
immediately after
--defaults-file or
--defaults-extra-file. Also,
when specifying file names, you should avoid the use of the
“~” shell metacharacter
because it might not be interpreted as you expect.
--defaults-extra-file=file_nameRead this option file after the global option file but (on Unix) before the user option file.
file_nameis the full path name to the file.Use only the given option file.
file_nameis the full path name to the file. If the file does not exist, the program exits with an error.Do not read any option files. If a program does not start because it is reading unknown options from an option file,
--no-defaultscan be used to prevent the program from reading them.Print the program name and all options that it gets from option files.
MySQL provides a number of preconfigured option files that can
be used as a basis for tuning the MySQL server. Look for files
such as my-small.cnf,
my-medium.cnf,
my-large.cnf, and
my-huge.cnf, which are sample option
files for small, medium, large, and very large systems. On
Windows, the extension is .ini rather
than .cnf extension.
Note
On Windows, the .cnf or
.ini option file extension might not be
displayed.
For a binary distribution, look for the files in or under your
installation directory. If you have a source distribution,
look in the support-files directory. You
can rename a copy of a sample file and place it in the
appropriate location for use as a base configuration file.
Regarding names and appropriate location, see the general
information provided in Section 4.2.3.3, “Using Option Files”.
Many MySQL programs have internal variables that can be set at
runtime using the
SET
statement. See Section 12.5.4, “SET Syntax”, and
Section 5.1.5, “Using System Variables”.
As of MySQL 4.0.2, most of these program variables also can be
set at server startup by using the same syntax that applies to
specifying program options. For example,
mysql has a
max_allowed_packet variable that controls the
maximum size of its communication buffer. To set the
max_allowed_packet variable for
mysql to a value of 16MB, use either of the
following commands:
shell>mysql --max_allowed_packet=16777216shell>mysql --max_allowed_packet=16M
The first command specifies the value in bytes. The second
specifies the value in megabytes. For variables that take a
numeric value, the value can be given with a suffix of
K, M, or
G (either uppercase or lowercase) to indicate
a multiplier of 1024, 10242 or
10243. (For example, when used to set
max_allowed_packet, the suffixes indicate
units of kilobytes, megabytes, or gigabytes.)
In an option file, variable settings are given without the leading dashes:
[mysql] max_allowed_packet=16777216
Or:
[mysql] max_allowed_packet=16M
If you like, underscores in a variable name can be specified as dashes. The following option groups are equivalent. Both set the size of the server's key buffer to 512MB:
[mysqld] key_buffer_size=512M [mysqld] key-buffer-size=512M
A variable can be specified by writing it in full or as any
unambiguous prefix. For example, the
max_allowed_packet variable can be set for
mysql as --max_a, but not as
--max because the latter is ambiguous:
shell> mysql --max=1000000
mysql: ambiguous option '--max=1000000' (max_allowed_packet, max_join_size)
Be aware that the use of variable prefixes can cause problems in the event that new variables are implemented for a program. A prefix that is unambiguous now might become ambiguous in the future.
Suffixes for specifying a value multiplier can be used when
setting a variable at server startup, but not to set the value
with SET
at runtime. On the other hand, with
SET you
can assign a variable's value using an expression, which is not
true when you set a variable at server startup. For example, the
first of the following lines is legal at server startup, but the
second is not:
shell>mysql --max_allowed_packet=16Mshell>mysql --max_allowed_packet=16*1024*1024
Conversely, the second of the following lines is legal at runtime, but the first is not:
mysql>SET GLOBAL max_allowed_packet=16M;mysql>SET GLOBAL max_allowed_packet=16*1024*1024;
Prior to MySQL 4.0.2, program variable names are not recognized
as option names. Instead, use the
--set-variable option to assign a value to a
variable:
shell>mysql --set-variable=max_allowed_packet=16777216shell>mysql --set-variable=max_allowed_packet=16M
In an option file, omit the leading dashes:
[mysql] set-variable = max_allowed_packet=16777216
Or:
[mysql] set-variable = max_allowed_packet=16M
With --set-variable, underscores in variable
names cannot be given as dashes for versions of MySQL older than
4.0.2, and the variable name must be specified in full.
The --set-variable option is still recognized
in MySQL 4.0.2 and up, but is deprecated.
By convention, long forms of options that assign a value are
written with an equals (=) sign, like this:
shell> mysql --host=tonfisk --user=jon
For options that require a value (that is, not having a default value), the equals sign is not required, and so the following is also valid:
shell> mysql --host tonfisk --user jon
In both cases, the mysql client attempts to connect to a MySQL server running on the host named “tonfisk” using an account with the user name “jon”.
Due to this behavior, problems can occasionally arise when no
value is provided for an option that expects one. Consider the
following example, where a user connects to a MySQL server
running on host tonfisk as user
jon:
shell>mysql --host 85.224.35.45 --user jonWelcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 3 Server version: 4.1.26 Source distribution Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql>SELECT CURRENT_USER();+----------------+ | CURRENT_USER() | +----------------+ | jon@% | +----------------+ 1 row in set (0.00 sec)
Omitting the required value for one of these option yields an error, such as the one shown here:
shell> mysql --host 85.224.35.45 --user
mysql: option '--user' requires an argument
In this case, mysql was unable to find a
value following the --user
option because nothing came after it on the command line.
However, if you omit the value for an option that is
not the last option to be used, you obtain
a different error that you may not be expecting:
shell> mysql --host --user jon
ERROR 2005 (HY000): Unknown MySQL server host '--user' (1)
Because mysql assumes that any string
following --host on the command
line is a host name, --host
--user is interpreted as
--host=--user, and the client
attempts to connect to a MySQL server running on a host named
“--user”.
Options having default values always require an equals sign when
assigning a value; failing to do so causes an error. For
example, the MySQL server
--log-error option has the
default value
,
where host_name.errhost_name is the name of the
host on which MySQL is running. Assume that you are running
MySQL on a computer whose host name is “tonfisk”,
and consider the following invocation of
mysqld_safe:
shell> mysqld_safe &
[1] 11699
shell> 080112 12:53:40 mysqld_safe Logging to '/usr/local/mysql/var/tonfisk.err'.
080112 12:53:40 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/var
shell>
After shutting down the server, restart it as follows:
shell> mysqld_safe --log-error &
[1] 11699
shell> 080112 12:53:40 mysqld_safe Logging to '/usr/local/mysql/var/tonfisk.err'.
080112 12:53:40 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/var
shell>
The result is the same, since
--log-error is not followed
by anything else on the command line, and it supplies its own
default value. (The & character tells the
operating system to run MySQL in the background; it is ignored
by MySQL itself.) Now suppose that you wish to log errors to a
file named my-errors.err. You might try
starting the server with --log-error my-errors,
but this does not have the intended effect, as shown here:
shell> mysqld_safe --log-error my-errors &
[1] 31357
shell> 080111 22:53:31 mysqld_safe Logging to '/usr/local/mysql/var/tonfisk.err'.
080111 22:53:32 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/var
080111 22:53:34 mysqld_safe mysqld from pid file /usr/local/mysql/var/tonfisk.pid ended
[1]+ Done ./mysqld_safe --log-error my-errors
The server attempted to start using
/usr/local/mysql/var/tonfisk.err as the
error log, but then shut down. Examining the last few lines of
this file shows the reason:
shell> tail /usr/local/mysql/var/tonfisk.err
080111 22:53:32 InnoDB: Started; log sequence number 0 46409
/usr/local/mysql/libexec/mysqld: Too many arguments (first extra is 'my-errors').
Use --verbose --help to get a list of available options
080111 22:53:32 [ERROR] Aborting
080111 22:53:32 InnoDB: Starting shutdown...
080111 22:53:34 InnoDB: Shutdown completed; log sequence number 0 46409
080111 22:53:34 [Note] /usr/local/mysql/libexec/mysqld: Shutdown complete
080111 22:53:34 mysqld_safe mysqld from pid file /usr/local/mysql/var/tonfisk.pid ended
Because the --log-error
option supplies a default value, you must use an equals sign to
assign a different value to it, as shown here:
shell> mysqld_safe --log-error=my-errors &
[1] 31437
shell> 080111 22:54:15 mysqld_safe Logging to '/usr/local/mysql/var/my-errors.err'.
080111 22:54:15 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/var
shell>
Now the server has been started successfully, and is logging
errors to the file
/usr/local/mysql/var/my-errors.err.
Similar issues can arise when specifying option values in option
files. For example, consider a my.cnf file
that contains the following:
[mysql] host user
When the mysql client reads this file, these
entries are parsed as --host
--user or
--host=--user, with the result
shown here:
shell> mysql
ERROR 2005 (HY000): Unknown MySQL server host '--user' (1)
However, in option files, an equals sign is not assumed. Suppose
the my.cnf file is as shown here:
[mysql] user jon
Trying to start mysql in this case causes a different error:
shell> mysql
mysql: unknown option '--user jon'
A similar error would occur if you were to write host
tonfisk in the option file rather than
host=tonfisk. Instead, you must use the
equals sign:
[mysql] user=jon
shell>mysqlWelcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 5 Server version: 4.1.26 Source distribution Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql>SELECT USER();+---------------+ | USER() | +---------------+ | jon@localhost | +---------------+ 1 row in set (0.00 sec)
This is not the same behavior as with the command line, where the equals sign is not required:
shell>mysql --user jon --host tonfiskWelcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 6 Server version: 4.1.26 Source distribution Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql>SELECT USER();+---------------+ | USER() | +---------------+ | jon@tonfisk | +---------------+ 1 row in set (0.00 sec)
Environment variables can be set at the command prompt to affect the current invocation of your command processor, or set permanently to affect future invocations. To set a variable permanently, you can set it in a startup file or by using the interface provided by your system for this purpose. Consult the documentation for your command interpreter for specific details. Section 2.13, “Environment Variables”, lists all environment variables that affect MySQL program operation.
To specify a value for an environment variable, use the syntax
appropriate for your command processor. For example, on Windows or
NetWare, you can set the USER variable to
specify your MySQL account name. To do so, use this syntax:
SET USER=your_name
The syntax on Unix depends on your shell. Suppose that you want to
specify the TCP/IP port number using the
MYSQL_TCP_PORT variable. Typical syntax (such
as for sh, bash,
zsh, and so on) is as follows:
MYSQL_TCP_PORT=3306 export MYSQL_TCP_PORT
The first command sets the variable, and the
export command exports the variable to the
shell environment so that its value becomes accessible to MySQL
and other processes.
For csh and tcsh, use setenv to make the shell variable available to the environment:
setenv MYSQL_TCP_PORT 3306
The commands to set environment variables can be executed at your command prompt to take effect immediately, but the settings persist only until you log out. To have the settings take effect each time you log in, use the interface provided by your system or place the appropriate command or commands in a startup file that your command interpreter reads each time it starts.
On Windows, you can set environment variables using the System Control Panel (under Advanced).
On Unix, typical shell startup files are
.bashrc or .bash_profile
for bash, or .tcshrc for
tcsh.
Suppose that your MySQL programs are installed in
/usr/local/mysql/bin and that you want to make
it easy to invoke these programs. To do this, set the value of the
PATH environment variable to include that
directory. For example, if your shell is bash,
add the following line to your .bashrc file:
PATH=${PATH}:/usr/local/mysql/bin
bash uses different startup files for login and
nonlogin shells, so you might want to add the setting to
.bashrc for login shells and to
.bash_profile for nonlogin shells to make
sure that PATH is set regardless.
If your shell is tcsh, add the following line
to your .tcshrc file:
setenv PATH ${PATH}:/usr/local/mysql/bin
If the appropriate startup file does not exist in your home directory, create it with a text editor.
After modifying your PATH setting, open a new
console window on Windows or log in again on Unix so that the
setting goes into effect.
This section describes mysqld, the MySQL server, and several programs that are used to start the server.
mysqld, also known as MySQL Server, is the main program that does most of the work in a MySQL installation. MySQL Server manages access to the MySQL data directory that contains databases and tables. The data directory is also the default location for other information such as log files and status files.
When MySQL server starts, it listens for network connections from client programs and manages access to databases on behalf of those clients.
The mysqld program has many options that can be specified at startup. For a complete list of options, run this command:
shell> mysqld --verbose --help
For versions older than MySQL 4.1.1, leave out the
--verbose option.
MySQL Server also has a set of system variables that affect its operation as it runs. System variables can be set at server startup, and many of them can be changed at runtime to effect dynamic server reconfiguration. MySQL Server also has a set of status variables that provide information about its operation. You can monitor these status variables to access runtime performance characteristics.
For a full description of MySQL Server command options, system variables, and status variables, see Section 5.1, “The MySQL Server”. For information about installing MySQL and setting up the initial configuration, see Chapter 2, Installing and Upgrading MySQL.
mysqld_safe is the recommended way to start a mysqld server on Unix and NetWare. mysqld_safe adds some safety features such as restarting the server when an error occurs and logging runtime information to an error log file. NetWare-specific behaviors are listed later in this section.
Note
Before MySQL 4.0, mysqld_safe is named safe_mysqld. To preserve backward compatibility, MySQL binary distributions include safe_mysqld as a symbolic link to mysqld_safe until MySQL 5.1.
By default, mysqld_safe tries to start an executable named mysqld-max if it exists, and mysqld otherwise. Be aware of the implications of this behavior:
On Linux, the
MySQL-MaxRPM relies on this mysqld_safe behavior. The RPM installs an executable named mysqld-max, which causes mysqld_safe to automatically use that executable rather than mysqld from that point on.If you install a MySQL-Max distribution that includes a server named mysqld-max, and then upgrade later to a non-Max version of MySQL, mysqld_safe will still attempt to run the old mysqld-max server. If you perform such an upgrade, you should manually remove the old mysqld-max server to ensure that mysqld_safe runs the new mysqld server.
To override the default behavior and specify explicitly the name
of the server you want to run, specify a
--mysqld or
--mysqld-version option to
mysqld_safe. You can also use
--ledir to indicate the
directory where mysqld_safe should look for
the server.
Many of the options to mysqld_safe are the same as the options to mysqld. See Section 5.1.2, “Server Command Options”.
Options unknown to mysqld_safe are passed to
mysqld if they are specified on the command
line, but ignored if they are specified in the
[mysqld_safe] group of an option file. See
Section 4.2.3.3, “Using Option Files”.
mysqld_safe reads all options from the
[mysqld], [server], and
[mysqld_safe] sections in option files. For
example, if you specify a [mysqld] section
like this, mysqld_safe will find and use the
--log-error option:
[mysqld] log-error=error.log
For backward compatibility, mysqld_safe also
reads [safe_mysqld] sections, although you
should rename such sections to [mysqld_safe]
when you begin using MySQL 4.0 or later.
Table 4.1. mysqld_safe Option Reference
| Format | Config File | Description | Introduction | Deprecated | Removed |
|---|---|---|---|---|---|
| --autoclose | autoclose | On NetWare, mysqld_safe provides a screen presence | |||
| --basedir=path | basedir | The path to the MySQL installation directory | |||
| --core-file-size=size | core-file-size | The size of the core file that mysqld should be able to create | |||
| --datadir=path | datadir | The path to the data directory | |||
| --defaults-extra-file=path | defaults-extra-file | The name of an option file to be read in addition to the usual option files | |||
| --defaults-file=file_name | defaults-file | The name of an option file to be read instead of the usual option files | |||
| --help | Display a help message and exit | ||||
| --ledir=path | ledir | Use this option to indicate the path name to the directory where the server is located | |||
| --log-error=file_name | log-error | Write the error log to the given file | |||
| --mysqld=prog_name | mysqld | The name of the server program (in the ledir directory) that you want to start | |||
| --mysqld-version=suffix | mysqld-version | This option is similar to the --mysqld option, but you specify only the suffix for the server program name | |||
| --nice=priority | nice | Use the nice program to set the server's scheduling priority to the given value | |||
| --no-defaults | no-defaults | Do not read any option files | |||
| --open-files-limit=count | open-files-limit | The number of files that mysqld should be able to open | |||
| --pid-file | pid-file | The path name of the process ID file | |||
| --port=number | port | The port number that the server should use when listening for TCP/IP connections | |||
| --skip-kill-mysqld | skip-kill-mysqld | Do not try to kill stray mysqld processes | |||
| --socket=path | socket | The Unix socket file that the server should use when listening for local connections | |||
| --timezone=timezone | timezone | Set the TZ time zone environment variable to the given option value | |||
| --user={user_name|user_id} | user | Run the mysqld server as the user having the name user_name or the numeric user ID user_id |
mysqld_safe supports the options in the following list. It also reads option files and supports the options for processing them described at Section 4.2.3.3.1, “Command-Line Options that Affect Option-File Handling”.
(NetWare only) On NetWare, mysqld_safe provides a screen presence. When you unload (shut down) the mysqld_safe NLM, the screen does not by default go away. Instead, it prompts for user input:
*<NLM has terminated; Press any key to close the screen>*
If you want NetWare to close the screen automatically instead, use the
--autocloseoption to mysqld_safe.The path to the MySQL installation directory.
The size of the core file that mysqld should be able to create. The option value is passed to ulimit -c.
The path to the data directory.
The name of an option file to be read in addition to the usual option files. This must be the first option on the command line if it is used.
The name of an option file to be read instead of the usual option files. This must be the first option on the command line if it is used.
The old form of the
--log-erroroption, to be used before MySQL 4.0.If mysqld_safe cannot find the server, use this option to indicate the path name to the directory where the server is located.
Write the error log to the given file. See Section 5.3.1, “The Error Log”.
The name of the server program (in the
ledirdirectory) that you want to start. This option is needed if you use the MySQL binary distribution but have the data directory outside of the binary distribution. If mysqld_safe cannot find the server, use the--lediroption to indicate the path name to the directory where the server is located.This option is similar to the
--mysqldoption, but you specify only the suffix for the server program name. The basename is assumed to be mysqld. For example, if you use--mysqld-version=max, mysqld_safe starts the mysqld-max program in theledirdirectory. If the argument to--mysqld-versionis empty, mysqld_safe uses mysqld in theledirdirectory.Use the
niceprogram to set the server's scheduling priority to the given value. This option was added in MySQL 4.0.14.Do not read any option files. This must be the first option on the command line if it is used.
The number of files that mysqld should be able to open. The option value is passed to ulimit -n. Note that you need to start mysqld_safe as
rootfor this to work properly.The path name of the process ID file.
The port number that the server should use when listening for TCP/IP connections. The port number must be 1024 or higher unless the server is started by the
rootsystem user.Do not try to kill stray mysqld processes at startup. This option works only on Linux.
The Unix socket file that the server should use when listening for local connections.
Set the
TZtime zone environment variable to the given option value. Consult your operating system documentation for legal time zone specification formats.Run the mysqld server as the user having the name
user_nameor the numeric user IDuser_id. (“User” in this context refers to a system login account, not a MySQL user listed in the grant tables.)
If you execute mysqld_safe with the
--defaults-file or
--defaults-extra-file option
to name an option file, the option must be the first one given
on the command line or the option file will not be used. For
example, this command will not use the named option file:
mysql> mysqld_safe --port=port_num --defaults-file=file_name
Instead, use the following command:
mysql> mysqld_safe --defaults-file=file_name --port=port_num
The mysqld_safe script is written so that it normally can start a server that was installed from either a source or a binary distribution of MySQL, even though these types of distributions typically install the server in slightly different locations. (See Section 2.1.5, “Installation Layouts”.) mysqld_safe expects one of the following conditions to be true:
The server and databases can be found relative to the working directory (the directory from which mysqld_safe is invoked). For binary distributions, mysqld_safe looks under its working directory for
binanddatadirectories. For source distributions, it looks forlibexecandvardirectories. This condition should be met if you execute mysqld_safe from your MySQL installation directory (for example,/usr/local/mysqlfor a binary distribution).If the server and databases cannot be found relative to the working directory, mysqld_safe attempts to locate them by absolute path names. Typical locations are
/usr/local/libexecand/usr/local/var. The actual locations are determined from the values configured into the distribution at the time it was built. They should be correct if MySQL is installed in the location specified at configuration time.
Because mysqld_safe tries to find the server and databases relative to its own working directory, you can install a binary distribution of MySQL anywhere, as long as you run mysqld_safe from the MySQL installation directory:
shell>cdshell>mysql_installation_directorybin/mysqld_safe &
If mysqld_safe fails, even when invoked from
the MySQL installation directory, you can specify the
--ledir and
--datadir options to
indicate the directories in which the server and databases are
located on your system.
Normally, you should not edit the mysqld_safe
script. Instead, configure mysqld_safe by
using command-line options or options in the
[mysqld_safe] section of a
my.cnf option file. In rare cases, it might
be necessary to edit mysqld_safe to get it to
start the server properly. However, if you do this, your
modified version of mysqld_safe might be
overwritten if you upgrade MySQL in the future, so you should
make a copy of your edited version that you can reinstall.
On NetWare, mysqld_safe is a NetWare Loadable Module (NLM) that is ported from the original Unix shell script. It starts the server as follows:
Runs a number of system and option checks.
Runs a check on
MyISAMandISAMtables.Provides a screen presence for the MySQL server.
Starts mysqld, monitors it, and restarts it if it terminates in error.
Sends error messages from mysqld to the
file in the data directory.host_name.errSends mysqld_safe screen output to the
file in the data directory.host_name.safe
MySQL distributions on Unix include a script named mysql.server. It can be used on systems such as Linux and Solaris that use System V-style run directories to start and stop system services. It is also used by the Mac OS X Startup Item for MySQL.
mysql.server can be found in the
support-files directory under your MySQL
installation directory or in a MySQL source distribution.
If you use the Linux server RPM package
(MySQL-server-),
the mysql.server script will be installed in
the VERSION.rpm/etc/init.d directory with the name
mysql. You need not install it manually.
See Section 2.4, “Installing MySQL from RPM Packages on Linux”, for more information on the
Linux RPM packages.
Some vendors provide RPM packages that install a startup script under a different name such as mysqld.
If you install MySQL from a source distribution or using a binary distribution format that does not install mysql.server automatically, you can install it manually. Instructions are provided in Section 2.10.2.2, “Starting and Stopping MySQL Automatically”.
mysql.server reads options from the
[mysql.server] and
[mysqld] sections of option files. For
backward compatibility, it also reads
[mysql_server] sections, although you should
rename such sections to [mysql.server] when
you begin using MySQL 4.0 or later.
mysql.server supports the following options:
The path to the MySQL installation directory.
The path to the MySQL data directory.
The path name of the file in which the server should write its process ID.
mysqld_multi is designed to manage several mysqld processes that listen for connections on different Unix socket files and TCP/IP ports. It can start or stop servers, or report their current status.
mysqld_multi searches for groups named
[mysqld in
N]my.cnf (or in the file named by the
--config-file option).
N can be any positive integer. This
number is referred to in the following discussion as the option
group number, or GNR. Group numbers
distinguish option groups from one another and are used as
arguments to mysqld_multi to specify which
servers you want to start, stop, or obtain a status report for.
Options listed in these groups are the same that you would use
in the [mysqld] group used for starting
mysqld. (See, for example,
Section 2.10.2.2, “Starting and Stopping MySQL Automatically”.) However, when using multiple
servers, it is necessary that each one use its own value for
options such as the Unix socket file and TCP/IP port number. For
more information on which options must be unique per server in a
multiple-server environment, see
Section 5.7, “Running Multiple MySQL Servers on the Same Machine”.
To invoke mysqld_multi, use the following syntax:
shell> mysqld_multi [options] {start|stop|report} [GNR[,GNR] ...]
start, stop, and
report indicate which operation to perform.
You can perform the designated operation for a single server or
multiple servers, depending on the
GNR list that follows the option
name. If there is no list, mysqld_multi
performs the operation for all servers in the option file.
Each GNR value represents an option
group number or range of group numbers. The value should be the
number at the end of the group name in the option file. For
example, the GNR for a group named
[mysqld17] is 17. To
specify a range of numbers, separate the first and last numbers
by a dash. The GNR value
10-13 represents groups
[mysqld10] through
[mysqld13]. Multiple groups or group ranges
can be specified on the command line, separated by commas. There
must be no whitespace characters (spaces or tabs) in the
GNR list; anything after a whitespace
character is ignored.
This command starts a single server using option group
[mysqld17]:
shell> mysqld_multi start 17
This command stops several servers, using option groups
[mysqld8] and [mysqld10]
through [mysqld13]:
shell> mysqld_multi stop 8,10-13
For an example of how you might set up an option file, use this command:
shell> mysqld_multi --example
mysqld_multi supports the following options:
Display a help message and exit.
Specify the name of an alternative option file. This affects where mysqld_multi looks for
[mysqldoption groups. Without this option, all options are read from the usualN]my.cnffile. The option does not affect where mysqld_multi reads its own options, which are always taken from the[mysqld_multi]group in the usualmy.cnffile.Display a sample option file.
Specify the name of the log file. If the file exists, log output is appended to it.
The mysqladmin binary to be used to stop servers.
The mysqld binary to be used. Note that you can specify mysqld_safe as the value for this option also. If you use mysqld_safe to start the server, you can include the
mysqldorlediroptions in the corresponding[mysqldoption group. These options indicate the name of the server that mysqld_safe should start and the path name of the directory where the server is located. (See the descriptions for these options in Section 4.3.2, “mysqld_safe — MySQL Server Startup Script”.) Example:N][mysqld38] mysqld = mysqld-max ledir = /opt/local/mysql/libexec
Print log information to
stdoutrather than to the log file. By default, output goes to the log file.The password of the MySQL account to use when invoking mysqladmin. Note that the password value is not optional for this option, unlike for other MySQL programs.
Silent mode; disable warnings. This option was added in MySQL 4.1.6.
Connect to each MySQL server via the TCP/IP port instead of the Unix socket file. (If a socket file is missing, the server might still be running, but accessible only via the TCP/IP port.) By default, connections are made using the Unix socket file. This option affects
stopandreportoperations.The user name of the MySQL account to use when invoking mysqladmin.
Be more verbose. This option was added in MySQL 4.1.6.
Display version information and exit.
Some notes about mysqld_multi:
Most important: Before using mysqld_multi be sure that you understand the meanings of the options that are passed to the mysqld servers and why you would want to have separate mysqld processes. Beware of the dangers of using multiple mysqld servers with the same data directory. Use separate data directories, unless you know what you are doing. Starting multiple servers with the same data directory does not give you extra performance in a threaded system. See Section 5.7, “Running Multiple MySQL Servers on the Same Machine”.
Important
Make sure that the data directory for each server is fully accessible to the Unix account that the specific mysqld process is started as. Do not use the Unix
rootaccount for this, unless you know what you are doing. See Section 5.4.5, “How to Run MySQL as a Normal User”.Make sure that the MySQL account used for stopping the mysqld servers (with the mysqladmin program) has the same user name and password for each server. Also, make sure that the account has the
SHUTDOWNprivilege. If the servers that you want to manage have different user names or passwords for the administrative accounts, you might want to create an account on each server that has the same user name and password. For example, you might set up a commonmulti_adminaccount by executing the following commands for each server:shell>
mysql -u root -S /tmp/mysql.sock -pEnter password: mysql>GRANT SHUTDOWN ON *.*->TO 'multi_admin'@'localhost' IDENTIFIED BY 'multipass';See Section 5.5, “The MySQL Access Privilege System”. You have to do this for each mysqld server. Change the connection parameters appropriately when connecting to each one. Note that the host name part of the account name must allow you to connect as
multi_adminfrom the host where you want to run mysqld_multi.The Unix socket file and the TCP/IP port number must be different for every mysqld. (Alternatively, if the host has multiple network addresses, you can use
--bind-addressto cause different servers to listen to different interfaces.)The
--pid-fileoption is very important if you are using mysqld_safe to start mysqld (for example,--mysqld=mysqld_safe) Every mysqld should have its own process ID file. The advantage of using mysqld_safe instead of mysqld is that mysqld_safe monitors its mysqld process and restarts it if the process terminates due to a signal sent usingkill -9or for other reasons, such as a segmentation fault. Please note that the mysqld_safe script might require that you start it from a certain place. This means that you might have to change location to a certain directory before running mysqld_multi. If you have problems starting, please see the mysqld_safe script. Check especially the lines:---------------------------------------------------------------- MY_PWD=`pwd` # Check if we are starting this relative (for the binary release) if test -d $MY_PWD/data/mysql -a -f ./share/mysql/english/errmsg.sys -a \ -x ./bin/mysqld ----------------------------------------------------------------
The test performed by these lines should be successful, or you might encounter problems. See Section 4.3.2, “mysqld_safe — MySQL Server Startup Script”.
You might want to use the
--useroption for mysqld, but to do this you need to run the mysqld_multi script as the Unixrootuser. Having the option in the option file does not matter; you merely get a warning if you are not the superuser and the mysqld processes are started under your own Unix account.
The following example shows how you might set up an option file
for use with mysqld_multi. The order in which
the mysqld programs are started or stopped
depends on the order in which they appear in the option file.
Group numbers need not form an unbroken sequence. The first and
fifth [mysqld
groups were intentionally omitted from the example to illustrate
that you can have “gaps” in the option file. This
gives you more flexibility.
N]
# This file should probably be in your home dir (~/.my.cnf) # or /etc/my.cnf # Version 2.1 by Jani Tolonen [mysqld_multi] mysqld = /usr/local/bin/mysqld_safe mysqladmin = /usr/local/bin/mysqladmin user = multi_admin password = multipass [mysqld2] socket = /tmp/mysql.sock2 port = 3307 pid-file = /usr/local/mysql/var2/hostname.pid2 datadir = /usr/local/mysql/var2 language = /usr/local/share/mysql/english user = john [mysqld3] socket = /tmp/mysql.sock3 port = 3308 pid-file = /usr/local/mysql/var3/hostname.pid3 datadir = /usr/local/mysql/var3 language = /usr/local/share/mysql/swedish user = monty [mysqld4] socket = /tmp/mysql.sock4 port = 3309 pid-file = /usr/local/mysql/var4/hostname.pid4 datadir = /usr/local/mysql/var4 language = /usr/local/share/mysql/estonia user = tonu [mysqld6] socket = /tmp/mysql.sock6 port = 3311 pid-file = /usr/local/mysql/var6/hostname.pid6 datadir = /usr/local/mysql/var6 language = /usr/local/share/mysql/japanese user = jani
- 4.4.1. comp_err — Compile MySQL Error Message File
- 4.4.2. make_win_src_distribution — Create Source Distribution for Windows
- 4.4.3. mysql_create_system_tables — Generate Statements to Initialize MySQL System Tables
- 4.4.4. mysqlbug — Generate Bug Report
- 4.4.5. mysql_fix_privilege_tables — Upgrade MySQL System Tables
- 4.4.6. mysql_install_db — Initialize MySQL Data Directory
- 4.4.7. mysql_secure_installation — Improve MySQL Installation Security
- 4.4.8. mysql_tzinfo_to_sql — Load the Time Zone Tables
The programs in this section are used when installing or upgrading MySQL.
comp_err creates the
errmsg.sys file that is used by
mysqld to determine the error messages to
display for different error codes. comp_err
normally is run automatically when MySQL is built. It compiles
the errmsg.sys file from the plaintext file
or files located in the
sql/share/
directories in MySQL source distributions.
language
For more information about how error messages are defined, see the MySQL Internals Manual.
Invoke comp_err like this:
shell> comp_err [options] from_file ... to_file
The from_file arguments are the input
files. to_file is the name of the
output file.
comp_err supports the options described in the following list.
-?,-IDisplay a help message and exit.
-#debug_optionsWrite a debugging log. A typical
debug_optionsstring is'd:t:O,.file_name'-VDisplay version information and exit.
make_win_src_distribution creates a Windows source package to be used on Windows systems. It is used after you configure and build the source distribution on a Unix or Unix-like system so that you have a server binary to work with. (See the instructions at Section 2.9.6.2, “Creating a Windows Source Package from the Latest Development Source”.)
Invoke make_win_src_distribution like this from the top-level directory of a MySQL source distribution:
shell> make_win_src_distribution [options]
make_win_src_distribution understands the following options:
Display a help message and exit.
Print information about script operations; do not create a package.
Directory name to copy files (intermediate).
Do not print verbose list of files processed.
The suffix name for the package.
Create a
tar.gzpackage instead of a.zippackage.By default, make_win_src_distribution creates a Zip-format archive with the name
mysql-, whereVERSION-win-src.zipVERSIONrepresents the version of your MySQL source tree.Specify the temporary location.
mysql_create_system_tables is a helper script that is invoked by mysql_install_db to generate the SQL statements required to initialize any grant tables that do not exist.
Invoke mysql_create_system_tables like this:
shell> mysql_create_system_tables {test|verbose} path_to_mysql_database host_name windows_option
The first argument is test (create entries
for the test database) or
verbose (display more information while the
script runs. The second argument is the path to the
mysql database directory. The third argument
is the host name to use in grant table entries. The fourth
argument is 1 if the script is being run to create tables for
use on Windows, 0 otherwise.
This program enables you to generate a bug report and send it to MySQL AB. It is a shell script and runs on Unix.
The normal way to report bugs is to visit http://bugs.mysql.com/, which is the address for our bugs database. This database is public and can be browsed and searched by anyone. If you log in to the system, you can enter new reports. If you have no Web access, you can generate a bug report by using the mysqlbug script.
mysqlbug helps you generate a report by
determining much of the following information automatically, but
if something important is missing, please include it with your
message. mysqlbug can be found in the
scripts directory (source distribution) and
in the bin directory under your MySQL
installation directory (binary distribution).
Invoke mysqlbug without arguments:
shell> mysqlbug
The script will place you in an editor with a copy of the report to be sent. Edit the lines near the beginning that indicate the nature of the problem. Then write the file to save your changes, quit the editor, and mysqlbug will send the report by email.
Some releases of MySQL introduce changes to the structure of the
system tables in the mysql database to add
new privileges or support new features. When you update to a new
version of MySQL, you should update your system tables as well
to make sure that their structure is up to date. Otherwise,
there might be capabilities that you cannot take advantage of.
First, make a backup of your mysql database,
and then use the following procedure.
On Unix or Unix-like systems, update the system tables by running the mysql_fix_privilege_tables script:
shell> mysql_fix_privilege_tables
You must run this script while the server is running. It
attempts to connect to the server running on the local host as
root. If your root account
requires a password, indicate the password on the command line.
For MySQL 4.1 and up, specify the password like this:
shell> mysql_fix_privilege_tables --password=root_password
Prior to MySQL 4.1, specify the password like this:
shell> mysql_fix_privilege_tables root_password
The mysql_fix_privilege_tables script
performs any actions necessary to convert your system tables to
the current format. You might see some Duplicate column
name warnings as it runs; you can ignore them.
After running the script, stop the server and restart it so that it uses any changes that were made to the system tables.
On Windows systems, there isn't an easy way to update the system
tables until MySQL 4.0.15. From version 4.0.15 on, MySQL
distributions include a
mysql_fix_privilege_tables.sql SQL script
that you can run using the mysql client. For
example, if your MySQL installation is located at
C:\Program Files\MySQL\MySQL Server
4.1, the commands look like this:
C:\>cd "C:\Program Files\MySQL\MySQL Server 4.1"C:\>bin\mysql -u root -p mysqlmysql>SOURCE scripts/mysql_fix_privilege_tables.sql
The mysql command will prompt you for the
root password; enter it when prompted.
If your installation is located in some other directory, adjust the path names appropriately.
As with the Unix procedure, you might see some
Duplicate column name warnings as
mysql processes the statements in the
mysql_fix_privilege_tables.sql script; you
can ignore them.
After running the script, stop the server and restart it.
mysql_install_db initializes the MySQL data directory and creates the system tables that it contains, if they do not exist.
To invoke mysql_install_db, use the following syntax:
shell> mysql_install_db [options]
Because the MySQL server, mysqld, needs to
access the data directory when it runs later, you should either
run mysql_install_db from the same account
that will be used for running mysqld or run
it as root and use the
--user option to
indicate the user name that mysqld will run
as. It might be necessary to specify other options such as
--basedir or
--datadir if
mysql_install_db does not use the correct
locations for the installation directory or data directory. For
example:
shell>bin/mysql_install_db --user=mysql \--basedir=/opt/mysql/mysql \--datadir=/opt/mysql/mysql/data
mysql_install_db supports the options in the following list. It also reads option files and supports the options for processing them described at Section 4.2.3.3.1, “Command-Line Options that Affect Option-File Handling”.
The path to the MySQL installation directory.
Causes mysql_install_db to run even if DNS does not work. In that case, grant table entries that normally use host names will use IP addresses.
The path to the MySQL data directory.
For internal use. This option is used by RPM files during the MySQL installation process.
Use IP addresses rather than host names when creating grant table entries. This option can be useful if your DNS does not work.
The login user name to use for running mysqld. Files and directories created by mysqld will be owned by this user. You must be
rootto use this option. By default, mysqld runs using your current login name and files and directories that it creates will be owned by you.Verbose mode. Print more information about what the program does.
For internal use. This option is used for creating Windows distributions.
This program enables you to improve the security of your MySQL installation in the following ways:
You can set a password for
rootaccounts.You can remove
rootaccounts that are accessible from outside the local host.You can remove anonymous-user accounts.
You can remove the
testdatabase, which by default can be accessed by anonymous users.
Invoke mysql_secure_installation without arguments:
shell> mysql_secure_installation
The script will prompt you to determine which actions to perform.
The mysql_tzinfo_to_sql program loads the
time zone tables in the mysql database. It is
used on systems that have a zoneinfo
database (the set of files describing time zones). Examples of
such systems are Linux, FreeBSD, Sun Solaris, and Mac OS X. One
likely location for these files is the
/usr/share/zoneinfo directory. If your
system does not have a zoneinfo database, you can use the
downloadable package described in
Section 9.7, “MySQL Server Time Zone Support”.
mysql_tzinfo_to_sql can be invoked several ways:
shell>mysql_tzinfo_to_sqlshell>tz_dirmysql_tzinfo_to_sqlshell>tz_file tz_namemysql_tzinfo_to_sql --leaptz_file
For the first invocation syntax, pass the zoneinfo directory path name to mysql_tzinfo_to_sql and send the output into the mysql program. For example:
shell> mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql
mysql_tzinfo_to_sql reads your system's time zone files and generates SQL statements from them. mysql processes those statements to load the time zone tables.
The second syntax causes mysql_tzinfo_to_sql
to load a single time zone file
tz_file that corresponds to a time
zone name tz_name:
shell> mysql_tzinfo_to_sql tz_file tz_name | mysql -u root mysql
If your time zone needs to account for leap seconds, invoke
mysql_tzinfo_to_sql using the third syntax,
which initializes the leap second information.
tz_file is the name of your time zone
file:
shell> mysql_tzinfo_to_sql --leap tz_file | mysql -u root mysql
After running mysql_tzinfo_to_sql, it is best to restart the server so that it does not continue to use any previously cached time zone data.
mysql_tzinfo_to_sql was added in MySQL 4.1.3.
- 4.5.1. mysql — The MySQL Command-Line Tool
- 4.5.2. mysqladmin — Client for Administering a MySQL Server
- 4.5.3. mysqlcheck — A Table Maintenance Program
- 4.5.4. mysqldump — A Database Backup Program
- 4.5.5. mysqlimport — A Data Import Program
- 4.5.6. mysqlshow — Display Database, Table, and Column Information
mysql is a simple SQL shell (with GNU
readline capabilities). It supports
interactive and noninteractive use. When used interactively,
query results are presented in an ASCII-table format. When used
noninteractively (for example, as a filter), the result is
presented in tab-separated format. The output format can be
changed using command options.
If you have problems due to insufficient memory for large result
sets, use the --quick option. This
forces mysql to retrieve results from the
server a row at a time rather than retrieving the entire result
set and buffering it in memory before displaying it. This is
done by returning the result set using the
mysql_use_result() C API
function in the client/server library rather than
mysql_store_result().
Using mysql is very easy. Invoke it from the prompt of your command interpreter as follows:
shell> mysql db_name
Or:
shell> mysql --user=user_name --password=your_password db_name
Then type an SQL statement, end it with
“;”, \g, or
\G and press Enter.
You can execute SQL statements in a script file (batch file) like this:
shell> mysql db_name < script.sql > output.tab
Table 4.2. mysql Option Reference
| Format | Config File | Description | Introduction | Deprecated | Removed |
|---|---|---|---|---|---|
| --auto-rehash | auto-rehash | Enable automatic rehashing | |||
| --batch | batch | Don't use history file | |||
| --character-sets-dir=name | character-sets-dir | Set the default character set | |||
| --column-names | column-names | Write column names in results | |||
| --compress | compress | Compress all information sent between the client and the server | |||
| --connect_timeout=value | connect_timeout | The number of seconds before connection timeout | |||
| --database=dbname | database | The database to use | |||
| --debug[=debug_options] | debug | Write a debugging log | |||
| --debug-info | debug-info | Print debugging information, memory and CPU statistics when the program exits | |||
| --default-character-set=charset_name | default-character-set | Use charset_name as the default character set | |||
| --delimiter=str | delimiter | Set the statement delimiter | |||
| --execute=statement | execute | Execute the statement and quit | |||
| --force | force | Continue even if an SQL error occurs | |||
| --help | Display help message and exit | ||||
| --host=host_name | host | Connect to the MySQL server on the given host | |||
| --html | html | Produce HTML output | |||
| --ignore-spaces | ignore-spaces | Ignore spaces after function names | |||
| --line-numbers | line-numbers | Write line numbers for errors | |||
| --local-infile[={0|1}] | local-infile | Enable or disable for LOCAL capability for LOAD DATA INFILE | |||
| --max_allowed_packet=value | max_allowed_packet | The maximum packet length to send to or receive from the server | |||
| --max_join_size=value | max_join_size | The automatic limit for rows in a join when using --safe-updates | |||
| --named-commands | named-commands | Enable named mysql commands | |||
| --net_buffer_length=value | net_buffer_length | The buffer size for TCP/IP and socket communication | |||
| --no-auto-rehash | Disable automatic rehashing | ||||
| --no-beep | no-beep | Do not beep when errors occur | |||
| --no-named-commands | no-named-commands | Disable named mysql commands | |||
| --no-pager | no-pager | Deprecated form of --skip-pager | |||
| --no-tee | no-tee | Do not copy output to a file | |||
| --one-database | one-database | Ignore statements except those for the default database named on the command line | |||
| --pager[=command] | pager | Use the given command for paging query output | |||
| --password[=password] | password | The password to use when connecting to the server | |||
| --port=port_num | port | The TCP/IP port number to use for the connection | |||
| --prompt=format_str | prompt | Set the prompt to the specified format | |||
| --protocol=type | protocol | The connection protocol to use | |||
| --quick | quick | Do not cache each query result | |||
| --raw | raw | Write column values without escape conversion | |||
| --reconnect | reconnect | If the connection to the server is lost, automatically try to reconnect | 4.1.0 | ||
| --safe-updates | safe-updates | Allow only UPDATE and DELETE statements that specify key values | |||
| --secure-auth | secure-auth | Do not send passwords to the server in old (pre-4.1.1) format | 4.1.1 | ||
| --select_limit=value | select_limit | The automatic limit for SELECT statements when using --safe-updates | |||
| --sigint-ignore | sigint-ignore | Ignore SIGINT signals (typically the result of typing Control-C) | 4.1.6 | ||
| --silent | silent | Silent mode | |||
| --skip-auto-rehash | skip-auto-rehash | Disable automatic rehashing | |||
| --skip-column-names | skip-column-names | Do not write column names in results | |||
| --skip-line-numbers | skip-line-numbers | Skip line numbers for errors | |||
| --skip-named-commands | skip-named-commands | Disable named mysql commands | |||
| --skip-pager | skip-pager | Disable paging | |||
| --skip-reconnect | skip-reconnect | Disable reconnecting | |||
| --socket=path | socket | For connections to localhost | |||
| --ssl-ca=file_name | ssl-ca | The path to a file that contains a list of trusted SSL CAs | |||
| --ssl-capath=directory_name | ssl-capath | The path to a directory that contains trusted SSL CA certificates in PEM format | |||
| --ssl-cert=file_name | ssl-cert | The name of the SSL certificate file to use for establishing a secure connection | |||
| --ssl-cipher=cipher_list | ssl-cipher | A list of allowable ciphers to use for SSL encryption | |||
| --ssl-key=file_name | ssl-key | The name of the SSL key file to use for establishing a secure connection | |||
| --ssl-verify-server-cert | ssl-verify-server-cert | The server's Common Name value in its certificate is verified against the host name used when connecting to the server | |||
| --table | table | Display output in tabular format | |||
| --tee=file_name | tee | Append a copy of output to the given file | |||
| --unbuffered | unbuffered | Flush the buffer after each query | |||
| --user=user_name | user | The MySQL user name to use when connecting to the server | |||
| --verbose | Verbose mode | ||||
| --version | Display version information and exit | ||||
| --vertical | vertical | Print query output rows vertically (one line per column value) | |||
| --wait | wait | If the connection cannot be established, wait and retry instead of aborting | |||
| --xml | xml | Produce XML output |
mysql supports the options in the following list. It also reads option files and supports the options for processing them described at Section 4.2.3.3.1, “Command-Line Options that Affect Option-File Handling”.
--help,-?Display a help message and exit.
Enable automatic rehashing. This option is on by default, which enables database, table, and column name completion. Use
--skip-auto-rehashto disable rehashing. That causes mysql to start faster, but you must issue therehashcommand if you want to use name completion.To complete a name, enter the first part and press Tab. If the name is unambiguous, mysql completes it. Otherwise, you can press Tab again to see the possible names that begin with what you have typed so far. Completion does not occur if there is no default database.
--batch,-BPrint results using tab as the column separator, with each row on a new line. With this option, mysql does not use the history file.
Batch mode results in nontabular output format and escaping of special characters. Escaping may be disabled by using raw mode; see the description for the
--rawoption.The directory where character sets are installed. See Section 9.2, “The Character Set Used for Data and Sorting”.
Write column names in results.
--compress,-CCompress all information sent between the client and the server if both support compression.
--database=,db_name-Ddb_nameThe database to use. This is useful primarily in an option file.
--debug[=,debug_options]-# [debug_options]Write a debugging log. A typical
debug_optionsstring is'd:t:o,. The default isfile_name''d:t:o,/tmp/mysql.trace'.--debug-info,-TPrint some debugging information when the program exits.
--default-character-set=charset_nameUse
charset_nameas the default character set. See Section 9.2, “The Character Set Used for Data and Sorting”.Set the statement delimiter. The default is the semicolon character (“
;”).--execute=,statement-estatementExecute the statement and quit. The default output format is like that produced with
--batch. See Section 4.2.3.1, “Using Options on the Command Line”, for some examples.--force,-fContinue even if an SQL error occurs.
--host=,host_name-hhost_nameConnect to the MySQL server on the given host.
--html,-HProduce HTML output.
--ignore-spaces,-iIgnore spaces after function names. The effect of this is described in the discussion for the
IGNORE_SPACESQL mode (see Section 5.1.7, “Server SQL Modes”).Write line numbers for errors. Disable this with
--skip-line-numbers.Enable or disable
LOCALcapability forLOAD DATA INFILE. With no value, the option enablesLOCAL. The option may be given as--local-infile=0or--local-infile=1to explicitly disable or enableLOCAL. EnablingLOCALhas no effect if the server does not also support it.MySQL Enterprise For expert advice on the security implications of enabling
LOCAL, subscribe to the MySQL Enterprise Monitor. For more information, see http://www.mysql.com/products/enterprise/advisors.html.--named-commands,-GEnable named mysql commands. Long-format commands are allowed, not just short-format commands. For example,
quitand\qboth are recognized. Use--skip-named-commandsto disable named commands. See Section 4.5.1.2, “mysql Commands”.--no-auto-rehash,-ADeprecated form of
-skip-auto-rehash. See the description for--auto-rehash.--no-beep,-bDo not beep when errors occur.
Disable named commands. Use the
\*form only, or use named commands only at the beginning of a line ending with a semicolon (“;”). As of MySQL 3.23.22, mysql starts with this option enabled by default. However, even with this option, long-format commands still work from the first line. See Section 4.5.1.2, “mysql Commands”.Deprecated form of
--skip-pager. See the--pageroption.Do not copy output to a file. Section 4.5.1.2, “mysql Commands”, discusses tee files further.
--one-database,-oIgnore statements except those for the default database named on the command line. This is useful for skipping updates to other databases in the binary log.
Use the given command for paging query output. If the command is omitted, the default pager is the value of your
PAGERenvironment variable. Valid pagers are less, more, cat [> filename], and so forth. This option works only on Unix. It does not work in batch mode. To disable paging, use--skip-pager. Section 4.5.1.2, “mysql Commands”, discusses output paging further.--password[=,password]-p[password]The password to use when connecting to the server. If you use the short option form (
-p), you cannot have a space between the option and the password. If you omit thepasswordvalue following the--passwordor-poption on the command line, you are prompted for one.Specifying a password on the command line should be considered insecure. See Section 5.6.6.2, “End-User Guidelines for Password Security”.
--pipe,-WOn Windows, connect to the server via a named pipe. This option applies only for connections to a local server, and only if the server supports named-pipe connections.
--port=,port_num-Pport_numThe TCP/IP port number to use for the connection.
Set the prompt to the specified format. The default is
mysql>. The special sequences that the prompt can contain are described in Section 4.5.1.2, “mysql Commands”.--protocol={TCP|SOCKET|PIPE|MEMORY}The connection protocol to use for connecting to the server. It is useful when the other connection parameters normally would cause a protocol to be used other than the one you want. For details on the allowable values, see Section 4.2.2, “Connecting to the MySQL Server”. This option was added in MySQL 4.1.
--quick,-qDo not cache each query result, print each row as it is received. This may slow down the server if the output is suspended. With this option, mysql does not use the history file.
--raw,-rFor tabular output, the “boxing” around columns enables one column value to be distinguished from another. For nontabular output (such as is produced in batch mode or when the
--batchor--silentoption is given), special characters are escaped in the output so they can be identified easily. Newline, tab,NUL, and backslash are written as\n,\t,\0, and\\. The--rawoption disables this character escaping.The following example demonstrates tabular versus nontabular output and the use of raw mode to disable escaping:
%
mysqlmysql> SELECT CHAR(92); +----------+ | CHAR(92) | +----------+ | \ | +----------+ %mysql -smysql> SELECT CHAR(92); CHAR(92) \\ %mysql -s -rmysql> SELECT CHAR(92); CHAR(92) \If the connection to the server is lost, automatically try to reconnect. A single reconnect attempt is made each time the connection is lost. To suppress reconnection behavior, use
--skip-reconnect. Added in MySQL 4.1.0.--safe-updates,--i-am-a-dummy,-UAllow only those
UPDATEandDELETEstatements that specify which rows to modify by using key values. If you have set this option in an option file, you can override it by using--safe-updateson the command line. See Section 4.5.1.5, “mysql Tips”, for more information about this option.Do not send passwords to the server in old (pre-4.1.1) format. This prevents connections except for servers that use the newer password format. This option was added in MySQL 4.1.1.
MySQL Enterprise For expert advice on database security, subscribe to the MySQL Enterprise Monitor. For more information, see http://www.mysql.com/products/enterprise/advisors.html.
Ignore
SIGINTsignals (typically the result of typing Control-C). This option was added in MySQL 4.1.6.--silent,-sSilent mode. Produce less output. This option can be given multiple times to produce less and less output.
This option results in nontabular output format and escaping of special characters. Escaping may be disabled by using raw mode; see the description for the
--rawoption.Do not write column names in results.
Do not write line numbers for errors. Useful when you want to compare result files that include error messages.
--socket=,path-SpathFor connections to
localhost, the Unix socket file to use, or, on Windows, the name of the named pipe to use.Options that begin with
--sslspecify whether to connect to the server via SSL and indicate where to find SSL keys and certificates. See Section 5.6.7.3, “SSL Command Options”.--table,-tDisplay output in table format. This is the default for interactive use, but can be used to produce table output in batch mode.
Append a copy of output to the given file. This option does not work in batch mode. Section 4.5.1.2, “mysql Commands”, discusses tee files further.
--unbuffered,-nFlush the buffer after each query.
--user=,user_name-uuser_nameThe MySQL user name to use when connecting to the server.
--verbose,-vVerbose mode. Produce more output about what the program does. This option can be given multiple times to produce more and more output. (For example,
-v -v -vproduces table output format even in batch mode.)--version,-VDisplay version information and exit.
--vertical,-EPrint query output rows vertically (one line per column value). Without this option, you can specify vertical output for individual statements by terminating them with
\G.--wait,-wIf the connection cannot be established, wait and retry instead of aborting.
--xml,-XProduce XML output.
You can also set the following variables by using
--
syntax:
var_name=value
The number of seconds before connection timeout. (Default value is
0.)The maximum packet length to send to or receive from the server. (Default value is 16MB.)
The automatic limit for rows in a join when using
--safe-updates. (Default value is 1,000,000.)The buffer size for TCP/IP and socket communication. (Default value is 16KB.)
The automatic limit for
SELECTstatements when using--safe-updates. (Default value is 1,000.)
It is also possible to set variables by using
--set-variable=
or var_name=value-O
syntax. In MySQL 4.1, this syntax is deprecated.
var_name=value
On Unix, the mysql client writes a record of
executed statements to a history file. By default, this file is
named .mysql_history and is created in your
home directory. To specify a different file, set the value of
the MYSQL_HISTFILE environment variable.
The .mysql_history should be protected with
a restrictive access mode because sensitive information might be
written to it, such as the text of SQL statements that contain
passwords. See Section 5.6.6.2, “End-User Guidelines for Password Security”.
If you do not want to maintain a history file, first remove
.mysql_history if it exists, and then use
either of the following techniques:
Set the
MYSQL_HISTFILEvariable to/dev/null. To cause this setting to take effect each time you log in, put the setting in one of your shell's startup files.Create
.mysql_historyas a symbolic link to/dev/null:shell>
ln -s /dev/null $HOME/.mysql_historyYou need do this only once.
mysql sends each SQL statement that you issue
to the server to be executed. There is also a set of commands
that mysql itself interprets. For a list of
these commands, type help or
\h at the mysql>
prompt:
mysql> help
List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
? (\?) Synonym for `help'.
clear (\c) Clear command.
connect (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set query delimiter.
edit (\e) Edit command with $EDITOR.
ego (\G) Send command to mysql server, display result vertically.
exit (\q) Exit mysql. Same as quit.
go (\g) Send command to mysql server.
help (\h) Display this help.
nopager (\n) Disable pager, print to stdout.
notee (\t) Don't write into outfile.
pager (\P) Set PAGER [to_pager]. Print the query results via PAGER.
print (\p) Print current command.
prompt (\R) Change your mysql prompt.
quit (\q) Quit mysql.
rehash (\#) Rebuild completion hash.
source (\.) Execute an SQL script file. Takes a file name as an argument.
status (\s) Get status information from the server.
system (\!) Execute a system shell command.
tee (\T) Set outfile [to_outfile]. Append everything into given
outfile.
use (\u) Use another database. Takes database name as argument.
charset_name(\C) Switch to another charset. Might be needed for processing
binlog.
For server side help, type 'help contents'
Each command has both a long and short form. The long form is not case sensitive; the short form is. The long form can be followed by an optional semicolon terminator, but the short form should not.
The use of short-form commands within multi-line /* ...
*/ comments is not supported.
help [
arg], \h [arg], \? [arg], ? [arg]Displays a help message listing the available mysql commands.
If you provide an argument to the
helpcommand, mysql uses it as a search string to access server-side help from the contents of the MySQL Reference Manual. For more information, see Section 4.5.1.3, “mysql Server-Side Help”.charset_name
charset_name, \Ccharset_nameThe
charset_namecommand changes the default character set and issues aSET NAMESstatement. This enables the character set to remain synchronized on the client and server if mysql is run with auto-reconnect enabled (which is not recommended), because the specified character set is used for reconnects.This command was added in MySQL 4.1.19. In MySQL 5.0 and up, the command name is charset
Clears the current input. Use this if you change your mind about executing the statement that you are entering.
connect [
db_namehost_name]], \r [db_namehost_name]]Reconnects to the server. The optional database name and host name arguments may be given to specify the default database or the host where the server is running. If omitted, the current values are used.
The
delimitercommand changes the string that mysql interprets as the separator between SQL statements. The default is the semicolon character (“;”).The delimiter can be specified as an unquoted or quoted argument. Quoting can be done with either single quote (
') or douple quote (") characters. To include a quote within a quoted string, either quote the string with the other quote character or escape the quote with a backslash (“\”) character. Backslash should be avoided outside of quoted strings because it is the escape character for MySQL. For an unquoted argument, the delmiter is read up to the first space or end of line. For a quoted argument, the delimiter is read up to the matching quote on the line.When the delimiter recognized by mysql is set to something other than the default of “
;”, instances of that character are sent to the server without interpretation. However, the server itself still interprets “;” as a statement delimiter and processes statements accordingly. This behavior on the server side comes into play for multiple-statement execution (see Section 17.7.12, “C API Support for Multiple Statement Execution”).Edits the current input statement. mysql checks the values of the
EDITORandVISUALenvironment variables to determine which editor to use. The default editor is vi if neither variable is set.The edit command works only in Unix.
Sends the current statement to the server to be executed and displays the result using vertical format.
Exits mysql.
Sends the current statement to the server to be executed.
Disables output paging. See the description for pager.
The nopager command works only in Unix.
Disables output copying to the tee file. See the description for tee.
By using the
--pageroption when you invoke mysql, it is possible to browse or search query results in interactive mode with Unix programs such as less, more, or any other similar program. If you specify no value for the option, mysql checks the value of thePAGERenvironment variable and sets the pager to that.Output paging can be enabled interactively with the pager command and disabled with nopager. The command takes an optional argument; if given, the paging program is set to that. With no argument, the pager is set to the pager that was set on the command line, or
stdoutif no pager was specified.Output paging works only in Unix because it uses the
popen()function, which does not exist on Windows. For Windows, the tee option can be used instead to save query output, although it is not as convenient as pager for browsing output in some situations.Prints the current input statement without executing it.
Reconfigures the mysql prompt to the given string. The special character sequences that can be used in the prompt are described later in this section.
If you specify the
promptcommand with no argument, mysql resets the prompt to the default ofmysql>.Exits mysql.
Rebuilds the completion hash that enables database, table, and column name completion while you are entering statements. (See the description for the
--auto-rehashoption.)source
file_name, \.file_nameReads the named file and executes the statements contained therein. On Windows, you can specify path name separators as
/or\\.The
statuscommand provides some information about the connection and the server you are using. If you are running in--safe-updatesmode,statusalso prints the values for the mysql variables that affect your queries.Executes the given command using your default command interpreter.
The system command works only in Unix.
tee [
file_name], \T [file_name]By using the
--teeoption when you invoke mysql, you can log statements and their output. All the data displayed on the screen is appended into a given file. This can be very useful for debugging purposes also. mysql flushes results to the file after each statement, just before it prints its next prompt.You can enable this feature interactively with the tee command. Without a parameter, the previous file is used. The tee file can be disabled with the notee command. Executing tee again re-enables logging.
use
db_name, \udb_nameUses
db_nameas the default database.
Here are a few tips about the pager command:
You can use it to write to a file and the results go only to the file:
mysql>
pager cat > /tmp/log.txtYou can also pass any options for the program that you want to use as your pager:
mysql>
pager less -n -i -SIn the preceding example, note the
-Soption. You may find it very useful for browsing wide query results. Sometimes a very wide result set is difficult to read on the screen. The-Soption to less can make the result set much more readable because you can scroll it horizontally using the left-arrow and right-arrow keys. You can also use-Sinteractively within less to switch the horizontal-browse mode on and off. For more information, read the less manual page:shell>
man lessThe
-Fand-Xoptions may be used with less to cause it to exit if output fits on one screen, which is convenient when no scrolling is necessary:mysql>
pager less -n -i -S -F -XYou can specify very complex pager commands for handling query output:
mysql>
pager cat | tee /dr1/tmp/res.txt \| tee /dr2/tmp/res2.txt | less -n -i -SIn this example, the command would send query results to two files in two different directories on two different file systems mounted on
/dr1and/dr2, yet still display the results onscreen via less.
You can also combine the tee and pager functions. Have a tee file enabled and pager set to less, and you are able to browse the results using the less program and still have everything appended into a file the same time. The difference between the Unix tee used with the pager command and the mysql built-in tee command is that the built-in tee works even if you do not have the Unix tee available. The built-in tee also logs everything that is printed on the screen, whereas the Unix tee used with pager does not log quite that much. Additionally, tee file logging can be turned on and off interactively from within mysql. This is useful when you want to log some queries to a file, but not others.
From MySQL 4.0.2 on, the prompt command
reconfigures the default mysql> prompt.
The string for defining the prompt can contain the following
special sequences.
| Option | Description |
\c | A counter that increments for each statement you issue |
\D | The full current date |
\d | The default database |
\h | The server host |
\m | Minutes of the current time |
\n | A newline character |
\O | The current month in three-letter format (Jan, Feb, …) |
\o | The current month in numeric format |
\P | am/pm |
\p | The current TCP/IP port or socket file |
\R | The current time, in 24-hour military time (0-23) |
\r | The current time, standard 12-hour time (1-12) |
\S | Semicolon |
\s | Seconds of the current time |
\t | A tab character |
\U | Your full
account name |
\u | Your user name |
\v | The server version |
\w | The current day of the week in three-letter format (Mon, Tue, …) |
\Y | The current year, four digits |
\y | The current year, two digits |
\_ | A space |
\ | A space (a space follows the backslash) |
\' | Single quote |
\" | Double quote |
\\ | A literal “\” backslash character |
\ | x, for any
“x” not listed
above |
You can set the prompt in several ways:
Use an environment variable. You can set the
MYSQL_PS1environment variable to a prompt string. For example:shell>
export MYSQL_PS1="(\u@\h) [\d]> "Use a command-line option. You can set the
--promptoption on the command line to mysql. For example:shell>
mysql --prompt="(\u@\h) [\d]> "(user@host) [database]>Use an option file. You can set the
promptoption in the[mysql]group of any MySQL option file, such as/etc/my.cnfor the.my.cnffile in your home directory. For example:[mysql] prompt=(\\u@\\h) [\\d]>\\_
In this example, note that the backslashes are doubled. If you set the prompt using the
promptoption in an option file, it is advisable to double the backslashes when using the special prompt options. There is some overlap in the set of allowable prompt options and the set of special escape sequences that are recognized in option files. (These sequences are listed in Section 4.2.3.3, “Using Option Files”.) The overlap may cause you problems if you use single backslashes. For example,\sis interpreted as a space rather than as the current seconds value. The following example shows how to define a prompt within an option file to include the current time inHH:MM:SS>format:[mysql] prompt="\\r:\\m:\\s> "
Set the prompt interactively. You can change your prompt interactively by using the
prompt(or\R) command. For example:mysql>
prompt (\u@\h) [\d]>\_PROMPT set to '(\u@\h) [\d]>\_' (user@host) [database]> (user@host) [database]> prompt Returning to default PROMPT of mysql> mysql>
mysql> help search_string
As of MySQL 4.1, if you provide an argument to the
help command, mysql uses
it as a search string to access server-side help from the
contents of the MySQL Reference Manual. The proper operation of
this command requires that the help tables in the
mysql database be initialized with help topic
information (see Section 5.1.8, “Server-Side Help”).
If there is no match for the search string, the search fails:
mysql> help me
Nothing found
Please try to run 'help contents' for a list of all accessible topics
Use help contents to see a list of the help categories:
mysql> help contents
You asked for help about help category: "Contents"
For more information, type 'help <item>', where <item> is one of the
following categories:
Account Management
Administration
Data Definition
Data Manipulation
Data Types
Functions
Functions and Modifiers for Use with GROUP BY
Geographic Features
Language Structure
Storage Engines
Table Maintenance
Transactions
If the search string matches multiple items, mysql shows a list of matching topics:
mysql> help logs
Many help items for your request exist.
To make a more specific request, please type 'help <item>',
where <item> is one of the following topics:
SHOW
SHOW BINARY LOGS
SHOW ENGINE
SHOW LOGS
Use a topic as the search string to see the help entry for that topic:
mysql> help show binary logs
Name: 'SHOW BINARY LOGS'
Description:
Syntax:
SHOW BINARY LOGS
SHOW MASTER LOGS
Lists the binary log files on the server. This statement is used as
part of the procedure described in [purge-binary-logs], that shows how
to determine which logs can be purged.
mysql> SHOW BINARY LOGS;
+---------------+-----------+
| Log_name | File_size |
+---------------+-----------+
| binlog.000015 | 724935 |
| binlog.000016 | 733481 |
+---------------+-----------+
The mysql client typically is used interactively, like this:
shell> mysql db_name
However, it is also possible to put your SQL statements in a
file and then tell mysql to read its input
from that file. To do so, create a text file
text_file that contains the
statements you wish to execute. Then invoke
mysql as shown here:
shell> mysql db_name < text_file
If you place a USE
statement as the
first statement in the file, it is unnecessary to specify the
database name on the command line:
db_name
shell> mysql < text_file
If you are already running mysql, you can
execute an SQL script file using the source
command or \. command:
mysql>sourcemysql>file_name\.file_name
Sometimes you may want your script to display progress information to the user. For this you can insert statements like this:
SELECT '<info_to_display>' AS ' ';
The statement shown outputs
<info_to_display>.
For more information about batch mode, see Section 3.5, “Using mysql in Batch Mode”.
This section describes some techniques that can help you use mysql more effectively.
Some query results are much more readable when displayed vertically, instead of in the usual horizontal table format. Queries can be displayed vertically by terminating the query with \G instead of a semicolon. For example, longer text values that include newlines often are much easier to read with vertical output:
mysql> SELECT * FROM mails WHERE LENGTH(txt) < 300 LIMIT 300,1\G
*************************** 1. row ***************************
msg_nro: 3068
date: 2000-03-01 23:29:50
time_zone: +0200
mail_from: Monty
reply: monty@no.spam.com
mail_to: "Thimble Smith" <tim@no.spam.com>
sbj: UTF-8
txt: >>>>> "Thimble" == Thimble Smith writes:
Thimble> Hi. I think this is a good idea. Is anyone familiar
Thimble> with UTF-8 or Unicode? Otherwise, I'll put this on my
Thimble> TODO list and see what happens.
Yes, please do that.
Regards,
Monty
file: inbox-jani-1
hash: 190402944
1 row in set (0.09 sec)
4.5.1.5.2. Using the --safe-updates Option
For beginners, a useful startup option is
--safe-updates (or
--i-am-a-dummy,
which has the same effect). This option was introduced in
MySQL 3.23.11. It is helpful for cases when you might have
issued a DELETE FROM
statement but
forgotten the tbl_nameWHERE clause. Normally, such
a statement deletes all rows from the table. With
--safe-updates, you can delete
rows only by specifying the key values that identify them.
This helps prevent accidents.
When you use the --safe-updates
option, mysql issues the following
statement when it connects to the MySQL server:
SET sql_safe_updates=1, sql_select_limit=1000, sql_max_join_size=1000000;
See Section 5.1.4, “Session System Variables”.
The SET
statement has the following effects:
You are not allowed to execute an
UPDATEorDELETEstatement unless you specify a key constraint in theWHEREclause or provide aLIMITclause (or both). For example:UPDATE
tbl_nameSETnot_key_column=valWHEREkey_column=val; UPDATEtbl_nameSETnot_key_column=valLIMIT 1;The server limits all large
SELECTresults to 1,000 rows unless the statement includes aLIMITclause.The server aborts multiple-table
SELECTstatements that probably need to examine more than 1,000,000 row combinations.
To specify limits different from 1,000 and 1,000,000, you can
override the defaults by using the
--select_limit and
--max_join_size options:
shell> mysql --safe-updates --select_limit=500 --max_join_size=10000
If the mysql client loses its connection to the server while sending a statement, it immediately and automatically tries to reconnect once to the server and send the statement again. However, even if mysql succeeds in reconnecting, your first connection has ended and all your previous session objects and settings are lost: temporary tables, the autocommit mode, and user-defined and session variables. Also, any current transaction rolls back. This behavior may be dangerous for you, as in the following example where the server was shut down and restarted between the first and second statements without you knowing it:
mysql>SET @a=1;Query OK, 0 rows affected (0.05 sec) mysql>INSERT INTO t VALUES(@a);ERROR 2006: MySQL server has gone away No connection. Trying to reconnect... Connection id: 1 Current database: test Query OK, 1 row affected (1.30 sec) mysql>SELECT * FROM t;+------+ | a | +------+ | NULL | +------+ 1 row in set (0.05 sec)
The @a user variable has been lost with the
connection, and after the reconnection it is undefined. If it
is important to have mysql terminate with
an error if the connection has been lost, you can start the
mysql client with the
--skip-reconnect
option.
For more information about auto-reconnect and its effect on state information when a reconnection occurs, see Section 17.7.11, “Controlling Automatic Reconnection Behavior”.
mysqladmin is a client for performing administrative operations. You can use it to check the server's configuration and current status, to create and drop databases, and more.
Invoke mysqladmin like this:
shell> mysqladmin [options] command [command-arg] [command [command-arg]] ...
mysqladmin supports the commands described in the following list. Some of the commands take an argument following the command name.
Create a new database named
db_name.Tell the server to write debug information to the error log.
Delete the database named
db_nameand all its tables.Display the server status variables and their values.
MySQL Enterprise For expert advice on using server system variables, subscribe to the MySQL Enterprise Monitor. For more information, see http://www.mysql.com/products/enterprise/advisors.html.
Flush all information in the host cache.
Flush all logs.
Reload the grant tables (same as
reload).Clear status variables.
Flush all tables.
Flush the thread cache. (Added in MySQL 3.23.16.)
Kill server threads. If multiple thread ID values are given, there must be no spaces in the list.
This is like the
passwordcommand but stores the password using the old (pre-4.1) password-hashing format. This command was added in MySQL 4.1.0. (See Section 5.6.6.3, “Password Hashing in MySQL”.)MySQL Enterprise For expert advice on the security implications of using the
old-passwordcommand, subscribe to the MySQL Enterprise Monitor. For more information, see http://www.mysql.com/products/enterprise/advisors.html.Set a new password. This changes the password to
new-passwordfor the account that you use with mysqladmin for connecting to the server. Thus, the next time you invoke mysqladmin (or any other client program) using the same account, you will need to specify the new password.If the
new-passwordvalue contains spaces or other characters that are special to your command interpreter, you need to enclose it within quotes. On Windows, be sure to use double quotes rather than single quotes; single quotes are not stripped from the password, but rather are interpreted as part of the password. For example:shell>
mysqladmin password "my new password"Caution
Do not use this command used if the server was started with the
--skip-grant-tablesoption. No password change will be applied. This is true even if you precede thepasswordcommand withflush-privilegeson the same command line to re-enable the grant tables because the flush operation occurs after you connect. However, you can use mysqladmin flush-privileges to re-enable the grant table and then use a separate mysqladmin password command to change the password.Check whether the server is alive. The return status from mysqladmin is 0 if the server is running, 1 if it is not. Beginning with MySQL 4.0.22, the status is 0 even in case of an error such as
Access denied, because that means the server is running but refused the connection, which is different from the server not running.Show a list of active server threads. This is like the output of the
SHOW PROCESSLISTstatement. If the--verboseoption is given, the output is like that ofSHOW FULL PROCESSLIST. (See Section 12.5.5.19, “SHOW PROCESSLISTSyntax”.)Reload the grant tables.
Flush all tables and close and open log files.
Stop the server.
Start replication on a slave server. (Added in MySQL 3.23.16.)
Display a short server status message.
Stop replication on a slave server. (Added in MySQL 3.23.16.)
Display the server system variables and their values.
MySQL Enterprise For expert advice on using server system variables, subscribe to the MySQL Enterprise Monitor. For more information, see http://www.mysql.com/products/enterprise/advisors.html.
Display version information from the server.
All commands can be shortened to any unique prefix. For example:
shell> mysqladmin proc stat
+----+-------+-----------+----+---------+------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+-------+-----------+----+---------+------+-------+------------------+
| 51 | monty | localhost | | Query | 0 | | show processlist |
+----+-------+-----------+----+---------+------+-------+------------------+
Uptime: 1473624 Threads: 1 Questions: 39487
Slow queries: 0 Opens: 541 Flush tables: 1
Open tables: 19 Queries per second avg: 0.0268
The mysqladmin status command result displays the following values:
The number of seconds the MySQL server has been running.
The number of active threads (clients).
The number of questions (queries) from clients since the server was started.
The number of queries that have taken more than
long_query_timeseconds. See Section 5.3.5, “The Slow Query Log”.The number of tables the server has opened.
The number of
flush-*,refresh, andreloadcommands the server has executed.The number of tables that currently are open.
The amount of memory allocated directly by mysqld. This value is displayed only when MySQL has been compiled with
--with-debug=full.The maximum amount of memory allocated directly by mysqld. This value is displayed only when MySQL has been compiled with
--with-debug=full.
If you execute mysqladmin shutdown when connecting to a local server using a Unix socket file, mysqladmin waits until the server's process ID file has been removed, to ensure that the server has stopped properly.
Table 4.3. mysqladmin Option Reference
| Format | Config File | Description | Introduction | Deprecated | Removed |
|---|---|---|---|---|---|
| --compress | compress | Compress all information sent between the client and the server | |||
| --connect_timeout=seconds | connect_timeout | The number of seconds before connection timeout | |||
| --count=# | count | The number of iterations to make for repeated command execution | |||
| --debug[=debug_options] | debug | Write a debugging log | |||
| --default-character-set=charset_name | default-character-set | Use charset_name as the default character set | 4.1.9 | ||
| --force | force | Continue even if an SQL error occurs | |||
| --help | Display help message and exit | ||||
| --host=host_name | host | Connect to the MySQL server on the given host | |||
| --password[=password] | password | The password to use when connecting to the server | |||
| --pipe | On Windows, connect to server via a named pipe | ||||
| --port=port_num | port | The TCP/IP port number to use for the connection | |||
| --protocol=type | protocol | The connection protocol to use | 4.1 | ||
| --relative | relative | Show the difference between the current and previous values when used with the --sleep option | |||
| --shutdown_timeout=seconds | shutdown_timeout | The maximum number of seconds to wait for server shutdown | |||
| --silent | silent | Silent mode | |||
| --sleep=delay | sleep | Execute commands repeatedly, sleeping for delay seconds in between | |||
| --socket=path | socket | For connections to localhost | |||
| --ssl-ca=file_name | ssl-ca | The path to a file that contains a list of trusted SSL CAs | |||
| --ssl-capath=directory_name | ssl-capath | The path to a directory that contains trusted SSL CA certificates in PEM format | |||
| --ssl-cert=file_name | ssl-cert | The name of the SSL certificate file to use for establishing a secure connection | |||
| --ssl-cipher=cipher_list | ssl-cipher | A list of allowable ciphers to use for SSL encryption | |||
| --ssl-key=file_name | ssl-key | The name of the SSL key file to use for establishing a secure connection | |||
| --ssl-verify-server-cert | ssl-verify-server-cert | The server's Common Name value in its certificate is verified against the host name used when connecting to the server | |||
| --user=user_name, | user | The MySQL user name to use when connecting to the server | |||
| --verbose | Verbose mode | ||||
| --version | Display version information and exit | ||||
| --vertical | vertical | Print query output rows vertically (one line per column value) | |||
| --wait | wait | If the connection cannot be established, wait and retry instead of aborting |
mysqladmin supports the options in the following list. It also reads option files and supports the options for processing them described at Section 4.2.3.3.1, “Command-Line Options that Affect Option-File Handling”.
--help,-?Display a help message and exit.
The directory where character sets are installed. See Section 9.2, “The Character Set Used for Data and Sorting”.
--compress,-CCompress all information sent between the client and the server if both support compression.
--count=,N-cNThe number of iterations to make for repeated command execution if the
--sleepoption is given.--debug[=,debug_options]-# [debug_options]Write a debugging log. A typical
debug_optionsstring is'd:t:o,. The default isfile_name''d:t:o,/tmp/mysqladmin.trace'.--default-character-set=charset_nameUse
charset_nameas the default character set. See Section 9.2, “The Character Set Used for Data and Sorting”. Added in MySQL 4.1.9.--force,-fDo not ask for confirmation for the
dropcommand. With multiple commands, continue even if an error occurs.db_name--host=,host_name-hhost_nameConnect to the MySQL server on the given host.
--password[=,password]-p[password]The password to use when connecting to the server. If you use the short option form (
-p), you cannot have a space between the option and the password. If you omit thepasswordvalue following the--passwordor-poption on the command line, you are prompted for one.Specifying a password on the command line should be considered insecure. See Section 5.6.6.2, “End-User Guidelines for Password Security”.
--pipe,-WOn Windows, connect to the server via a named pipe. This option applies only for connections to a local server, and only if the server supports named-pipe connections.
--port=,port_num-Pport_numThe TCP/IP port number to use for the connection.
--protocol={TCP|SOCKET|PIPE|MEMORY}The connection protocol to use for connecting to the server. It is useful when the other connection parameters normally would cause a protocol to be used other than the one you want. For details on the allowable values, see Section 4.2.2, “Connecting to the MySQL Server”. This option was added in MySQL 4.1.
--relative,-rShow the difference between the current and previous values when used with the
--sleepoption. Currently, this option works only with theextended-statuscommand.--silent,-sExit silently if a connection to the server cannot be established.
--sleep=,delay-idelayExecute commands repeatedly, sleeping for
delayseconds in between. The--countoption determines the number of iterations. If--countis not given, mysqladmin executes commands indefinitely until interrupted.--socket=,path-SpathFor connections to
localhost, the Unix socket file to use, or, on Windows, the name of the named pipe to use.Options that begin with
--sslspecify whether to connect to the server via SSL and indicate where to find SSL keys and certificates. See Section 5.6.7.3, “SSL Command Options”.--user=,user_name-uuser_nameThe MySQL user name to use when connecting to the server.
--verbose,-vVerbose mode. Print more information about what the program does.
--version,-VDisplay version information and exit.
--vertical,-EPrint output vertically. This is similar to
--relative, but prints output vertically.--wait[=,count]-w[count]If the connection cannot be established, wait and retry instead of aborting. If a
countvalue is given, it indicates the number of times to retry. The default is one time.
You can also set the following variables by using
--
syntax:
var_name=value
It is also possible to set variables by using
--set-variable=
or var_name=value-O
syntax. However, this syntax is deprecated as of MySQL 4.0.
var_name=value
The mysqlcheck client performs table
maintenance: It checks, repairs, optimizes, and analyzes tables.
Each table is locked and therefore unavailable to other sessions
while it is being processed. Table maintenance operations can be
time-consuming, particularly for large tables. If you use the
--databases or --all-databases
option to process all tables in one or more databases, an
invocation of mysqlcheck might take a long
time. mysqlcheck is available as of MySQL
3.23.38.
mysqlcheck is similar in function to myisamchk, but works differently. The main operational difference is that mysqlcheck must be used when the mysqld server is running, whereas myisamchk should be used when it is not. The benefit of using mysqlcheck is that you do not have to stop the server to check or repair your tables.
mysqlcheck uses the SQL statements
CHECK TABLE,
REPAIR TABLE,
ANALYZE TABLE, and
OPTIMIZE TABLE in a convenient
way for the user. It determines which statements to use for the
operation you want to perform, and then sends the statements to
the server to be executed. For details about which storage
engines each statement works with, see the descriptions for
those statements in Section 12.5.2, “Table Maintenance Statements”.
The MyISAM storage engine supports all four
maintenance operations, so mysqlcheck can be
used to perform any of them on MyISAM tables.
Other storage engines do not necessarily support all operations.
In such cases, an error message is displayed. For example, if
test.t is a MEMORY table,
an attempt to check it produces this result:
shell> mysqlcheck test t
test.t
note : The storage engine for the table doesn't support check
If mysqlcheck is unable to repair a table,
see Section 2.11.4, “Rebuilding or Repairing Tables or Indexes” for manual table repair
strategies. This will be the case, for example, for
InnoDB tables, which can be checked with
CHECK TABLE, but not repaired
with REPAIR TABLE.
Caution
It is best to make a backup of a table before performing a table repair operation; under some circumstances the operation might cause data loss. Possible causes include but are not limited to file system errors.
There are three general ways to invoke mysqlcheck:
shell>mysqlcheck [shell>options]db_name[tables]mysqlcheck [shell>options] --databasesdb_name1[db_name2db_name3...]mysqlcheck [options] --all-databases
If you do not name any tables following
db_name or if you use the
--databases or
--all-databases option,
entire databases are checked.
mysqlcheck has a special feature compared to
other client programs. The default behavior of checking tables
(--check) can be changed by
renaming the binary. If you want to have a tool that repairs
tables by default, you should just make a copy of
mysqlcheck named
mysqlrepair, or make a symbolic link to
mysqlcheck named
mysqlrepair. If you invoke
mysqlrepair, it repairs tables.
The following names can be used to change mysqlcheck default behavior.
| mysqlrepair | The default option is --repair |
| mysqlanalyze | The default option is --analyze |
| mysqloptimize | The default option is --optimize |
Table 4.4. mysqlcheck Option Reference
| Format | Config File | Description | Introduction | Deprecated | Removed |
|---|---|---|---|---|---|
| --all-databases | all-databases | Check all tables in all databases | |||
| --all-in-1 | all-in-1 | Execute a single statement for each database that names all the tables from that database | |||
| --analyze | analyze | Analyze the tables | |||
| --auto-repair | auto-repair | If a checked table is corrupted, automatically fix it | |||
| --character-sets-dir=path | character-sets-dir | The directory where character sets are installed | |||
| --check | check | Check the tables for errors | |||
| --check-only-changed | check-only-changed | Check only tables that have changed since the last check | |||
| --compress | compress | Compress all information sent between the client and the server | |||
| --databases | databases | Process all tables in the named databases | |||
| --debug[=debug_options] | debug | Write a debugging log | |||
| --default-character-set=charset_name | default-character-set | Use charset_name as the default character set | |||
| --extended | extended | Check and repair tables | |||
| --fast | fast | Check only tables that have not been closed properly | |||
| --force | force | Continue even if an SQL error occurs | |||
| --help | Display help message and exit | ||||
| --host=host_name | host | Connect to the MySQL server on the given host | |||
| --medium-check | medium-check | Do a check that is faster than an --extended operation | |||
| --optimize | optimize | Optimize the tables | |||
| --password[=password] | password | The password to use when connecting to the server | |||
| --pipe | On Windows, connect to server via a named pipe | ||||
| --port=port_num | port | The TCP/IP port number to use for the connection | |||
| --protocol=type | protocol | The connection protocol to use | 4.1 | ||
| --quick | quick | The fastest method of checking | |||
| --repair | repair | Perform a repair that can fix almost anything except unique keys that are not unique | |||
| --silent | silent | Silent mode | |||
| --socket=path | socket | For connections to localhost | |||
| --ssl-ca=file_name | ssl-ca | The path to a file that contains a list of trusted SSL CAs | |||
| --ssl-capath=directory_name | ssl-capath | The path to a directory that contains trusted SSL CA certificates in PEM format | |||
| --ssl-cert=file_name | ssl-cert | The name of the SSL certificate file to use for establishing a secure connection | |||
| --ssl-cipher=cipher_list | ssl-cipher | A list of allowable ciphers to use for SSL encryption | |||
| --ssl-key=file_name | ssl-key | The name of the SSL key file to use for establishing a secure connection | |||
| --ssl-verify-server-cert | ssl-verify-server-cert | The server's Common Name value in its certificate is verified against the host name used when connecting to the server | |||
| --tables | tables | Overrides the --databases or -B option | |||
| --use-frm | use-frm | For repair operations on MyISAM tables | |||
| --user=user_name, | user | The MySQL user name to use when connecting to the server | |||
| --verbose | Verbose mode | ||||
| --version | Display version information and exit |
mysqlcheck supports the options in the following list. It also reads option files and supports the options for processing them described at Section 4.2.3.3.1, “Command-Line Options that Affect Option-File Handling”.
--help,-?Display a help message and exit.
--all-databases,-ACheck all tables in all databases. This is the same as using the
--databasesoption and naming all the databases on the command line.--all-in-1,-1Instead of issuing a statement for each table, execute a single statement for each database that names all the tables from that database to be processed.
--analyze,-aAnalyze the tables.
MySQL Enterprise For expert advice on optimizing tables, subscribe to the MySQL Enterprise Monitor. For more information, see http://www.mysql.com/products/enterprise/advisors.html.
If a checked table is corrupted, automatically fix it. Any necessary repairs are done after all tables have been checked.
The directory where character sets are installed. See Section 9.2, “The Character Set Used for Data and Sorting”.
--check,-cCheck the tables for errors. This is the default operation.
Check only tables that have changed since the last check or that have not been closed properly.
Compress all information sent between the client and the server if both support compression.
--databases,-BProcess all tables in the named databases. Normally, mysqlcheck treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names.
--debug[=,debug_options]-# [debug_options]Write a debugging log. A typical
debug_optionsstring is'd:t:o,. The default isfile_name''d:t:o'.--default-character-set=charset_nameUse
charset_nameas the default character set. See Section 9.2, “The Character Set Used for Data and Sorting”.--extended,-eIf you are using this option to check tables, it ensures that they are 100% consistent but takes a long time.
If you are using this option to repair tables, it runs an extended repair that may not only take a long time to execute, but may produce a lot of garbage rows also!
--fast,-FCheck only tables that have not been closed properly.
--force,-fContinue even if an SQL error occurs.
--host=,host_name-hhost_nameConnect to the MySQL server on the given host.
--medium-check,-mDo a check that is faster than an
--extendedoperation. This finds only 99.99% of all errors, which should be good enough in most cases.--optimize,-oOptimize the tables.
--password[=,password]-p[password]The password to use when connecting to the server. If you use the short option form (
-p), you cannot have a space between the option and the password. If you omit thepasswordvalue following the--passwordor-poption on the command line, you are prompted for one.Specifying a password on the command line should be considered insecure. See Section 5.6.6.2, “End-User Guidelines for Password Security”.
--pipe,-WOn Windows, connect to the server via a named pipe. This option applies only for connections to a local server, and only if the server supports named-pipe connections.
--port=,port_num-Pport_numThe TCP/IP port number to use for the connection.
--protocol={TCP|SOCKET|PIPE|MEMORY}The connection protocol to use for connecting to the server. It is useful when the other connection parameters normally would cause a protocol to be used other than the one you want. For details on the allowable values, see Section 4.2.2, “Connecting to the MySQL Server”. This option was added in MySQL 4.1.
--quick,-qIf you are using this option to check tables, it prevents the check from scanning the rows to check for incorrect links. This is the fastest check method.
If you are using this option to repair tables, it tries to repair only the index tree. This is the fastest repair method.
--repair,-rPerform a repair that can fix almost anything except unique keys that are not unique.
--silent,-sSilent mode. Print only error messages.
--socket=,path-SpathFor connections to
localhost, the Unix socket file to use, or, on Windows, the name of the named pipe to use.Options that begin with
--sslspecify whether to connect to the server via SSL and indicate where to find SSL keys and certificates. See Section 5.6.7.3, “SSL Command Options”.Overrides the
--databasesor-Boption. All name arguments following the option are regarded as table names.For repair operations on
MyISAMtables, get the table structure from the.frmfile so that the table can be repaired even if the.MYIheader is corrupted. This option was added in MySQL 4.0.5.--user=,user_name-uuser_nameThe MySQL user name to use when connecting to the server.
--verbose,-vVerbose mode. Print information about the various stages of program operation.
--version,-VDisplay version information and exit.
The mysqldump client is a backup program originally written by Igor Romanenko. It can be used to dump a database or a collection of databases for backup or transfer to another SQL server (not necessarily a MySQL server). The dump typically contains SQL statements to create the table, populate it, or both. However, mysqldump can also be used to generate files in CSV, other delimited text, or XML format.
If you are doing a backup on the server and your tables all are
MyISAM tables, consider using the
mysqlhotcopy instead because it can
accomplish faster backups and faster restores. See
Section 4.6.8, “mysqlhotcopy — A Database Backup Program”.
There are three general ways to invoke mysqldump:
shell>mysqldump [shell>options]db_name[tables]mysqldump [shell>options] --databasesdb_name1[db_name2db_name3...]mysqldump [options] --all-databases
If you do not name any tables following
db_name or if you use the
--databases or
--all-databases option, entire
databases are dumped.
To get a list of the options your version of mysqldump supports, execute mysqldump --help.
Some mysqldump options are shorthand for
groups of other options. --opt
and --compact fall into this
category. For example, use of
--opt is the same as
specifying --add-drop-table
--add-locks
--create-options
--disable-keys
--extended-insert
--lock-tables
--quick
--set-charset. Note that as of
MySQL 4.1, all of the options that
--opt stands for also are on
by default because --opt is on
by default.
To reverse the effect of a group option, uses its
--skip- form
(xxx--skip-opt or
--skip-compact).
It is also possible to select only part of the effect of a group
option by following it with options that enable or disable
specific features. Here are some examples:
To select the effect of
--optexcept for some features, use the--skipoption for each feature. For example, to disable extended inserts and memory buffering, use--opt--skip-extended-insert--skip-quick. (As of MySQL 4.1,--skip-extended-insert--skip-quickis sufficient because--optis on by default.)To reverse
--optfor all features except index disabling and table locking, use--skip-opt--disable-keys--lock-tables.
When you selectively enable or disable the effect of a group
option, order is important because options are processed first
to last. For example,
--disable-keys
--lock-tables
--skip-opt would not have the
intended effect; it is the same as
--skip-opt by itself.
mysqldump can retrieve and dump table
contents row by row, or it can retrieve the entire content from
a table and buffer it in memory before dumping it. Buffering in
memory can be a problem if you are dumping large tables. To dump
tables row by row, use the
--quick option (or
--opt, which enables
--quick). The
--opt option (and hence
--quick) is enabled by default
in MySQL 4.1; to enable memory buffering, use
--skip-quick.
If you are using a recent version of
mysqldump to generate a dump to be reloaded
into a very old MySQL server, you should not use the
--opt or
--extended-insert option. Use
--skip-opt instead.
Before MySQL 4.1.2, out-of-range numeric values such as
-inf and inf, as well as
NaN (not-a-number) values are dumped by
mysqldump as NULL. You can
see this using the following sample table:
mysql>CREATE TABLE t (f DOUBLE);mysql>INSERT INTO t VALUES(1e+111111111111111111111);mysql>INSERT INTO t VALUES(-1e111111111111111111111);mysql>SELECT f FROM t;+------+ | f | +------+ | inf | | -inf | +------+
For this table, mysqldump produces the following data output:
-- -- Dumping data for table `t` -- INSERT INTO t VALUES (NULL); INSERT INTO t VALUES (NULL);
The significance of this behavior is that if you dump and
restore the table, the new table has contents that differ from
the original contents. This problem is fixed as of MySQL 4.1.2;
you cannot insert inf in the table, so this
mysqldump behavior is only relevant when you
deal with old servers.
Table 4.5. mysqldump Option Reference
| Format | Config File | Description | Introduction | Deprecated | Removed |
|---|---|---|---|---|---|
| --add-drop-database | add-drop-database | Add a DROP DATABASE statement before each CREATE DATABASE statement | 4.1.13 | ||
| --add-drop-table | add-drop-table | Add a DROP TABLE statement before each CREATE TABLE statement | |||
| --add-locks | add-locks | Surround each table dump with LOCK TABLES and UNLOCK TABLES statements | |||
| --all-databases | all-databases | Dump all tables in all databases | |||
| --allow-keywords | allow-keywords | Allow creation of column names that are keywords | |||
| --comments | comments | Add comments to the dump file | |||
| --compact | compact | Produce less verbose output | |||
| --compatible=name[,name,...] | compatible | Produce output that is more compatible with other database systems or with older MySQL servers | |||
| --complete-insert | complete-insert | Use complete INSERT statements that include column names | |||
| --create-options | create-options | Include all MySQL-specific table options in the CREATE TABLE statements | |||
| --databases | databases | Dump several databases | |||
| --debug[=debug_options] | debug | Write a debugging log | |||
| --default-character-set=charset_name | default-character-set | Use charset_name as the default character set | |||
| --delayed-insert | delayed-insert | Write INSERT DELAYED statements rather than INSERT statements | |||
| --delete-master-logs | delete-master-logs | On a master replication server, delete the binary logs after performing the dump operation | |||
| --disable-keys | disable-keys | For each table, surround the INSERT statements with disable and enable keys statements | |||
| --extended-insert | extended-insert | Use multiple-row INSERT syntax that include several VALUES lists | |||
| --fields-enclosed-by=string | fields-enclosed-by | This option is used with the -T option and has the same meaning as the corresponding clause for LOAD DATA INFILE | |||
| --fields-escaped-by | fields-escaped-by | This option is used with the -T option and has the same meaning as the corresponding clause for LOAD DATA INFILE | |||
| --fields-optionally-enclosed-by=string | fields-optionally-enclosed-by | This option is used with the -T option and has the same meaning as the corresponding clause for LOAD DATA INFILE | |||
| --fields-terminated-by=string | fields-terminated-by | This option is used with the -T option and has the same meaning as the corresponding clause for LOAD DATA INFILE | |||
| --lock-all-tables | first-slave | Deprecated. Now renamed to --lock-all-tables | |||
| --flush-logs | flush-logs | Flush the MySQL server log files before starting the dump | |||
| --help | Display help message and exit | ||||
| --hex-blob | hex-blob | Dump binary columns using hexadecimal notation (for example, 'abc' becomes 0x616263) | |||
| --ignore-table=db_name.tbl_name | ignore-table | Do not dump the given table | |||
| --insert-ignore | insert-ignore | Write INSERT statements with the IGNORE option | 4.1.12 | ||
| --lines-terminated-by=string | lines-terminated-by | This option is used with the -T option and has the same meaning as the corresponding clause for LOAD DATA INFILE | |||
| --lock-all-tables | lock-all-tables | Lock all tables across all databases | |||
| --lock-tables | lock-tables | Lock all tables before dumping them | |||
| --master-data[=value] | master-data | Write the binary log file name and position to the output | |||
| --max_allowed_packet=value | max_allowed_packet | The maximum packet length to send to or receive from the server | |||
| --net_buffer_length=value | net_buffer_length | The buffer size for TCP/IP and socket communication | |||
| --no-autocommit | no-autocommit | Enclose the INSERT statements for each dumped table within SET autocommit = 0 and COMMIT statements | |||
| --no-create-db | no-create-db | This option suppresses the CREATE DATABASE statements | |||
| --no-create-info | no-create-info | Do not write CREATE TABLE statements that re-create each dumped table | |||
| --no-data | no-data | Do not write any table row information (that is, do not dump table contents) | |||
| --no-set-names | no-set-names | Turn off complete-insert | |||
| --opt | opt | This option is shorthand; it is the same as specifying --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. | |||
| --order-by-primary | order-by-primary | Sorts each table's rows by its primary key, or by its first unique index | |||
| --password[=password] | password | The password to use when connecting to the server | |||
| --pipe | On Windows, connect to server via a named pipe | ||||
| --port=port_num | port | The TCP/IP port number to use for the connection | |||
| --quick | quick | Retrieve rows for a table from the server a row at a time | |||
| --quote-names | quote-names | Quote database, table, and column names within backtick characters | |||
| --result-file=file | result-file | Direct output to a given file | |||
| --set-charset | set-charset | Add SET NAMES default_character_set to the output | |||
| --single-transaction | single-transaction | This option issues a BEGIN SQL statement before dumping data from the server | |||
| --skip-add-drop-table | skip-add-drop-table | Do not add | |||
| --skip-add-locks | skip-add-locks | Do not add locks | |||
| --skip-comments | skip-comments | Do not add comments to the dump file | |||
| --skip-compact | skip-compact | Turn off compact | |||
| --skip-disable-keys | skip-disable-keys | Do not disable keys | |||
| --skip-extended-insert | skip-extended-insert | Turn off extended-insert | |||
| --skip-opt | skip-opt | Turn off the options set by opt | |||
| --skip-quick | skip-quick | Do not retrieve rows for a table from the server a row at a time | |||
| --skip-quote-names | skip-quote-names | Turn off quote names | |||
| --skip-set-charset | skip-set-charset | Suppress the SET NAMES statement | |||
| --ssl-ca=file_name | ssl-ca | The path to a file that contains a list of trusted SSL CAs | |||
| --ssl-capath=directory_name | ssl-capath | The path to a directory that contains trusted SSL CA certificates in PEM format | |||
| --ssl-cert=file_name | ssl-cert | The name of the SSL certificate file to use for establishing a secure connection | |||
| --ssl-cipher=cipher_list | ssl-cipher | A list of allowable ciphers to use for SSL encryption | |||
| --ssl-key=file_name | ssl-key | The name of the SSL key file to use for establishing a secure connection | |||
| --ssl-verify-server-cert | ssl-verify-server-cert | The server's Common Name value in its certificate is verified against the host name used when connecting to the server | |||
| --tab=path | tab | Produce tab-separated data files | |||
| --tables | tables | Override the --databases or -B option | |||
| --verbose | Verbose mode | ||||
| --version | Display version information and exit | ||||
| --where='where_condition' | where | Dump only rows selected by the given WHERE condition | |||
| --xml | xml | Produce XML output |
mysqldump supports the options in the following list. It also reads option files and supports the options for processing them described at Section 4.2.3.3.1, “Command-Line Options that Affect Option-File Handling”.
--help,-?Display a help message and exit.
Add a
DROP DATABASEstatement before eachCREATE DATABASEstatement. Added in MySQL 4.1.13.Add a
DROP TABLEstatement before eachCREATE TABLEstatement.Surround each table dump with
LOCK TABLESandUNLOCK TABLESstatements. This results in faster inserts when the dump file is reloaded. See Section 7.2.14, “Speed ofINSERTStatements”.--all-databases,-ADump all tables in all databases. This is the same as using the
--databasesoption and naming all the databases on the command line.Allow creation of column names that are keywords. This works by prefixing each column name with the table name.
The directory where character sets are installed. See Section 9.2, “The Character Set Used for Data and Sorting”.
--comments,-iWrite additional information in the dump file such as program version, server version, and host. This option is enabled by default. To suppress this additional information, use
--skip-comments. This option was added in MySQL 4.0.17.Produce less verbose output. This option enables the
--skip-add-drop-table,--skip-add-locks,--skip-comments,--skip-disable-keys, and--skip-set-charsetoptions. Added in MySQL 4.1.2.Produce output that is more compatible with other database systems or with older MySQL servers. The value of
namecan beansi,mysql323,mysql40,postgresql,oracle,mssql,db2,maxdb,no_key_options,no_table_options, orno_field_options. To use several values, separate them by commas. These values have the same meaning as the corresponding options for setting the server SQL mode. See Section 5.1.7, “Server SQL Modes”.This option does not guarantee compatibility with other servers. It only enables those SQL mode values that are currently available for making dump output more compatible. For example,
--compatible=oracledoes not map data types to Oracle types or use Oracle comment syntax.This option requires a server version of 4.1.0 or higher. With older servers, it does nothing.
Use complete
INSERTstatements that include column names.--compress,-CCompress all information sent between the client and the server if both support compression.
Include all MySQL-specific table options in the
CREATE TABLEstatements. Before MySQL 4.1.2, use--allinstead.--databases,-BDump several databases. Normally, mysqldump treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names.
CREATE DATABASEandUSEstatements are included in the output before each new database.--debug[=,debug_options]-# [debug_options]Write a debugging log. A typical
debug_optionsstring is'd:t:o,. The default value isfile_name''d:t:o,/tmp/mysqldump.trace'.--default-character-set=charset_nameUse
charset_nameas the default character set. See Section 9.2, “The Character Set Used for Data and Sorting”. If no character set is specified, mysqldump from MySQL 4.1.2 or later usesutf8, and earlier versions uselatin1.Write
INSERT DELAYEDstatements rather thanINSERTstatements.On a master replication server, delete the binary logs after performing the dump operation. This option automatically enables
--first-slavebefore MySQL 4.1.8 and enables--master-datathereafter. It was added in MySQL 3.23.57 (for MySQL 3.23) and MySQL 4.0.13 (for MySQL 4.0).--disable-keys,-KFor each table, surround the
INSERTstatements with/*!40000 ALTER TABLEandtbl_nameDISABLE KEYS */;/*!40000 ALTER TABLEstatements. This makes loading the dump file into a MySQL 4.0 or newer server faster because the indexes are created after all rows are inserted. This option is effective only for nonunique indexes oftbl_nameENABLE KEYS */;MyISAMtables. only.Use multiple-row
INSERTsyntax that include severalVALUESlists. This results in a smaller dump file and speeds up inserts when the file is reloaded.--fields-terminated-by=...,--fields-enclosed-by=...,--fields-optionally-enclosed-by=...,--fields-escaped-by=...These options are used with the
-Toption and have the same meaning as the corresponding clauses forLOAD DATA INFILE. See Section 12.2.5, “LOAD DATA INFILESyntax”.--first-slave,-xDeprecated. Renamed to
--lock-all-tablesin MySQL 4.1.8.--flush-logs,-FFlush the MySQL server log files before starting the dump. This option requires the
RELOADprivilege. Note that if you use this option in combination with the--all-databases(or-A) option, the logs are flushed for each database dumped. The exception is when using--lock-all-tablesor--master-data: In this case, the logs are flushed only once, corresponding to the moment that all tables are locked. If you want your dump and the log flush to happen at exactly the same moment, you should use--flush-logstogether with either--lock-all-tablesor--master-data.--force,-fContinue even if an SQL error occurs during a table dump.
--host=,host_name-hhost_nameDump data from the MySQL server on the given host. The default host is
localhost.Dump binary columns using hexadecimal notation (for example,
'abc'becomes0x616263). The affected data types areBINARY,VARBINARY, andBLOBin MySQL 4.1 and up, andCHAR BINARY,VARCHAR BINARY, andBLOBin MySQL 4.0. This option was added in MySQL 4.0.23 and 4.1.8.--ignore-table=db_name.tbl_nameDo not dump the given table, which must be specified using both the database and table names. To ignore multiple tables, use this option multiple times. This option was added in MySQL 4.1.9.
Write
INSERTstatements with theIGNOREoption. This option was added in MySQL 4.1.12.This option is used with the
-Toption and has the same meaning as the corresponding clause forLOAD DATA INFILE. See Section 12.2.5, “LOAD DATA INFILESyntax”.Lock all tables across all databases. This is achieved by acquiring a global read lock for the duration of the whole dump. This option automatically turns off
--single-transactionand--lock-tables. Added in MySQL 4.1.8.--lock-tables,-lLock all tables before dumping them. The tables are locked with
READ LOCALto allow concurrent inserts in the case ofMyISAMtables. For transactional tables such asInnoDBandBDB,--single-transactionis a much better option, because it does not need to lock the tables at all.Please note that when dumping multiple databases,
--lock-tableslocks tables for each database separately. Therefore, this option does not guarantee that the tables in the dump file are logically consistent between databases. Tables in different databases may be dumped in completely different states.This option has no effect for output data files produced by using the
--taboption. See the description for that option.Use this option to dump a master replication server to produce a dump file that can be used to set up another server as a slave of the master. It causes the dump output to include a
CHANGE MASTER TOstatement that indicates the binary log coordinates (file name and position) of the dumped server. These are the master server coordinates from which the slave should start replicating.If the option value is 2, the
CHANGE MASTER TOstatement is written as an SQL comment, and thus is informative only; it has no effect when the dump file is reloaded. If the option value is 1, the statement takes effect when the dump file is reloaded. If the option value is not specified, the default value is 1. The value may be given as of MySQL 4.1.8; before that, do not specify an option value.This option requires the
RELOADprivilege and the binary log must be enabled.The
--master-dataoption automatically turns off