All MySQL clients that communicate with the server using the
mysqlclient
library use the following environment variables:
Name | Description |
MYSQL_UNIX_PORT | The default socket; used for connections to localhost
|
MYSQL_TCP_PORT | The default TCP/IP port |
MYSQL_PWD | The default password |
MYSQL_DEBUG | Debug-trace options when debugging |
TMPDIR | The directory where temporary tables/files are created |
Use of MYSQL_PWD
is insecure.
See section 5.3.8 Connecting to the MySQL Server.
On Unix,
the `mysql' client uses the file named in the MYSQL_HISTFILE
environment variable to save the command-line history. The default value for
the history file is `$HOME/.mysql_history', where $HOME
is the
value of the HOME
environment variable. See section E Environment Variables.
If you do not want to maintain a file that contains a record of your queries, first remove `.mysql_history' if it exists, then use either of the following techniques:
MYSQL_HISTFILE
variable 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.
shell> ln -s /dev/null $HOME/.mysql_historyYou need do this only once.
All MySQL programs take many different options. However, every
MySQL program provides a --help
option that you can use
to get a full description of the program's different options. For example, try
mysql --help
.
You can override default options for all standard programs by specifying options on the command line or in an option file. section 4.3 Specifying Program Options.
The following list briefly describes the MySQL client programs and utilities:
msql2mysql
mSQL
programs to MySQL. It doesn't
handle all cases, but it gives a good start when converting.
mysql
mysql
, The Command-line Tool.
mysqlcc
mysqlcc
, The MySQL Control Center.
mysqlaccess
mysqladmin
mysqladmin
can also be used to retrieve version,
process, and status information from the server.
See section 8.4 mysqladmin
, Administering a MySQL Server.
mysqlbinlog
mysqlbinlog
, Executing the queries from a binary log.
mysqldump
mysqldump
, Dumping Table Structure and Data.
mysqlimport
LOAD DATA
INFILE
. See section 8.9 mysqlimport
, Importing Data from Text Files.
mysqlshow
replace
msql2mysql
, but that has more
general applicability as well. replace
changes strings in place in
files or on the standard input. Uses a finite state machine to match longer
strings first. Can be used to swap strings. For example, this command
swaps a
and b
in the given files:
shell> replace a b b a -- file1 file2 ...
mysql
, The Command-line Tool
mysql
is a simple SQL shell (with GNU readline
capabilities).
It supports interactive and non-interactive use. When used interactively,
query results are presented in an ASCII-table format. When used
non-interactively (for example, as a filter), the result is presented in
tab-separated format. (The output format can be changed using command-line
options.) You can run scripts simply like this:
shell> mysql database < script.sql > output.tab
If you have problems due to insufficient memory in the client, use the
--quick
option! This forces mysql
to use
mysql_use_result()
rather than mysql_store_result()
to
retrieve the result set.
Using mysql
is very easy. Just start it as follows:
mysql database
or mysql --user=user_name --password=your_password
database
. Type an SQL statement, end it with `;', `\g', or `\G'
and press Enter.
mysql
supports the following options:
-?, --help
-A, --no-auto-rehash
--prompt=...
-b, --no-beep
-B, --batch
--character-sets-dir=...
-C, --compress
-#, --debug[=...]
-D, --database=...
--default-character-set=...
-e, --execute=...
-E, --vertical
\G
.
-f, --force
-g, --no-named-commands
-G, --enable-named-commands
-i, --ignore-space
-h, --host=...
-H, --html
-X, --xml
-L, --skip-line-numbers
--no-pager
--no-tee
-n, --unbuffered
-N, --skip-column-names
-O, --set-variable=name=value
--help
lists variables.
Please note that --set-variable=name=value
and -O name=value
syntax is deprecated as of MySQL 4.0. Use --name=value
instead.
-o, --one-database
--pager[=...]
ENV
variable PAGER
. Valid
pagers are less, more, cat [> filename], etc. See interactive help (\h)
also. This option does not work in batch mode. Pager works only in Unix.
-p[password], --password[=...]
-p
you can't have a space between the option and the
password.
-P port_num, --port=port_num
--protocol=(TCP | SOCKET | PIPE | MEMORY)
-q, --quick
-r, --raw
--batch
--reconnect
-s, --silent
-S --socket=...
-t --table
-T, --debug-info
--tee=...
-u, --user=#
-U, --safe-updates[=#], --i-am-a-dummy[=#]
UPDATE
and DELETE
that uses keys. See below for
more information about this option. You can reset this option if you have
it in your `my.cnf' file by using --safe-updates=0
.
-v, --verbose
-V, --version
-w, --wait
You can also set the following variables with -O
or
--set-variable
.
Please note that --set-variable=name=value
and -O name=value
syntax is deprecated as of MySQL 4.0. Use --name=value
instead.
Variable Name | Default | Description |
connect_timeout | 0 | Number of seconds before connection timeout. |
local-infile | 0 | Disable (0) or enable (1) LOCAL capability for LOAD DATA INFILE
|
max_allowed_packet | 16777216 | Max packet length to send to/receive from server |
net_buffer_length | 16384 | Buffer for TCP/IP and socket communication |
select_limit | 1000 | Automatic limit for SELECT when using --safe-updates
|
max_join_size | 1000000 | Automatic limit for rows in a join when using --safe-updates
|
If the mysql
client loses connection to the server while
sending it a query, it will immediately and automatically try to
reconnect once to the server and send the query again.
Note that even if it succeeds in reconnecting, as your first
connection has ended, all your previous session objects are lost: temporary
tables, user and session variables. Therefore, the above behavior may
be dangerous for you, as in this example where the server was shut
down and restarted 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.
To protect from this risk, you can start the mysql
client
with the --disable-reconnect
option.
If you type 'help' on the command-line, mysql
will print out the
commands that it supports:
mysql> help MySQL commands: help (\h) Display this text. ? (\h) 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. 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.
The edit
, nopager
, pager
, and system
commands
work only in Unix.
The status
command gives you some information about the
connection and the server you are using. If you are running in the
--safe-updates
mode, status
will also print the values for
the mysql
variables that affect your queries.
A useful startup option for beginners (introduced in MySQL
Version 3.23.11) is --safe-updates
(or --i-am-a-dummy
for
users that once may have done a DELETE FROM table_name
but forgot
the WHERE
clause). When using this option, mysql
sends
the following command to the MySQL server when opening the connection:
SET SQL_SAFE_UPDATES=1,SQL_SELECT_LIMIT=#select_limit#, SQL_MAX_JOIN_SIZE=#max_join_size#"
where #select_limit#
and #max_join_size#
are variables that
can be set from the mysql
command-line. See section 7.5.6 SET
Syntax.
The effect of the above is:
UPDATE
or DELETE
statement
if you don't have a key constraint in the WHERE
part. One can,
however, force an UPDATE/DELETE
by using LIMIT
:
UPDATE table_name SET not_key_column=# WHERE not_key_column=# LIMIT 1;
#select_limit#
rows.
SELECT
statements that will probably need to examine more than
#max_join_size
row combinations will be aborted.
Some useful hints about the mysql
client:
Some data is much more readable when displayed vertically, instead of the usual horizontal box type output. For example longer text, which includes new lines, is often much easier to be 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 with UTF-8 Thimble> or Unicode? Otherwise, I'll put this on my TODO list and see what Thimble> happens. Yes, please do that. Regards, Monty file: inbox-jani-1 hash: 190402944 1 row in set (0.09 sec)
For logging, you can use the tee
option. The tee
can be
started with option --tee=...
, or from the command-line
interactively with command tee
. All the data displayed on the
screen will also be appended into a given file. This can be very useful
for debugging purposes also. The tee
can be disabled from the
command-line with command notee
. Executing tee
again
starts logging again. Without a parameter the previous file will be
used. Note that tee
will flush the results into the file after
each command, just before the command-line appears again waiting for the
next command.
Browsing, or searching the results in the interactive mode in Unix less,
more, or any other similar program, is now possible with option
--pager[=...]
. Without argument, mysql
client will look
for the PAGER
environment variable and set pager
to that.
pager
can be started from the interactive command-line with
command pager
and disabled with command nopager
. The
command takes an argument optionally and the pager
will be set to
that. Command pager
can be called without an argument, but this
requires that the option --pager
was used, or the pager
will default to stdout. pager
works only in Unix, since it uses
the popen()
function, which doesn't exist in Windows. In Windows, the
tee
option can be used instead, although it may not be as handy
as pager
can be in some situations.
A few tips about pager
:
mysql> pager cat > /tmp/log.txtand the results will only go to a file. You can also pass any options for the programs that you want to use with the
pager
:
mysql> pager less -n -i -S
-S
. You may find it very useful when
browsing the results; try the option with horizontal output (end
commands with \g
, or `;') and with vertical output (end commands with
\G
). Sometimes a very wide result set is hard to be read from the screen,
with option -S
to less
you can browse the results within the interactive
less
from left to right, preventing lines longer than your screen from
being continued to the next line. This can make the result set much more
readable. You can switch the mode between on and off within the interactive
less
with -S
. See the 'h' for more help about less
.
mysql> pager cat | tee /dr1/tmp/res.txt | \ tee /dr2/tmp/res2.txt | less -n -i -S
You can also combine the two functions above; have the tee
enabled, pager
set to 'less' and you will be able to browse the
results in Unix 'less' and still have everything appended into a file
the same time. The difference between Unix tee
used with the
pager
and the mysql
client in-built tee
, is that
the in-built tee
works even if you don't have the Unix tee
available. The in-built tee
also logs everything that is printed
on the screen, where the Unix tee
used with pager
doesn't
log quite that much. Last, but not least, the interactive tee
is
more handy to switch on and off, when you want to log something into a
file, but want to be able to turn the feature off sometimes.
From MySQL version 4.0.2 it is possible to change the prompt in the
mysql
command-line client.
You can use the following prompt options:
Option | Description |
\v | mysqld version |
\d | database in use |
\h | host connected to |
\p | port connected on |
\u | username |
\U | full username@host |
\\ | `\' |
\n | new line break |
\t | tab |
\ | space |
\_ | space |
\R | military hour time (0-23) |
\r | standard hour time (1-12) |
\m | minutes |
\y | two digit year |
\Y | four digit year |
\D | full date format |
\s | seconds |
\w | day of the week in three letter format (Mon, Tue, ...) |
\P | am/pm |
\o | month in number format |
\O | month in three letter format (Jan, Feb, ...) |
\c | counter that counts up for each command you do |
`\' followed by any other letter just becomes that letter.
You may set the prompt in the following places:
MYSQL_PS1
environment variable to a prompt string. For
example:
shell> export MYSQL_PS1="(\u@\h) [\d]> "
prompt
option in any MySQL configuration file, in the
mysql
group. For example:
[mysql] prompt=(\u@\h) [\d]>\_
--prompt
option on the command line to mysql
.
For example:
shell> mysql --prompt="(\u@\h) [\d]> " (user@host) [database]>
prompt
(or \R
) command to change your
prompt interactively. 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>
The mysql
client typically is used interactively, like this:
shell> mysql database
However, it's also possible to put your SQL commands in a file and tell
mysql
to read its input from that file. To do so, create a text
file `text_file' that contains the commands you wish to execute.
Then invoke mysql
as shown here:
shell> mysql database < text_file
You can also start your text file with a USE db_name
statement. In
this case, it is unnecessary to specify the database name on the command
line:
shell> mysql < text_file
If you are already running mysql
, you can execute an SQL
script file using the source
command:
mysql> source filename;
For more information about batch mode, section 3.5 Using mysql
in Batch Mode.
mysqlcc
, The MySQL Control Center
mysqlcc
, the MySQL Control Center, is a platform-independent client that
provides a graphical user interface (GUI) to the MySQL database server.
It supports interactive use, including syntax highlighting and tab-completion.
It provides database and table management, and allows server administration.
Currently, mysqlcc
runs on Windows and Linux platforms.
mysqlcc
is not included with MySQL distributions, but can be downloaded
separately at http://www.mysql.com/downloads/.
mysqlcc
supports the following options:
-?, --help
-b, --blocking_queries
-C, --compress
-c, --connection_name=name
--server
.
-d, --database=...
-H, --history_size=#
-h, --host=...
-p[password], --password[=...]
-p
you can't have a space between the option and the
password.
-g, --plugins_path=name
-P port_num, --port=port_num
-q, --query
-r, --register
-s, --server=name
-S --socket=...
-y, --syntax
-Y, --syntax_file=name
-T, --translations_path=name
-u, --user=#
-V, --version
You can also set the following variables with -O
or
--set-variable
. please note that --set-variable
Please note that --set-variable=name=value
and -O name=value
syntax is deprecated as of MySQL 4.0. Use --name=value
instead.
Variable Name | Default | Description |
connect_timeout | 0 | Number of seconds before connection timeout. |
local-infile | 0 | Disable (0) or enable (1) LOCAL capability for LOAD DATA INFILE
|
max_allowed_packet | 16777216 | Max packet length to send to/receive from server |
net_buffer_length | 16384 | Buffer for TCP/IP and socket communication |
select_limit | 1000 | Automatic limit for SELECT when using --safe-updates
|
max_join_size | 1000000 | Automatic limit for rows in a join when using --safe-updates
|
mysqladmin
, Administering a MySQL ServerA utility for performing administrative operations. The syntax is:
shell> mysqladmin [OPTIONS] command [command-option] command ...
You can get a list of the options your version of mysqladmin
supports
by executing mysqladmin --help
.
The current mysqladmin
supports the following commands:
create databasename
drop databasename
extended-status
flush-hosts
flush-logs
flush-tables
flush-privileges
kill id,id,...
password
ping
processlist
SHOW PROCESSLIST
statement.
If the --verbose
option is given, the output is like that of
SHOW FULL PROCESSLIST
.
reload
refresh
shutdown
slave-start
slave-stop
status
variables
version
All commands can be shortened to their unique prefix. For example:
shell> mysqladmin proc stat +----+-------+-----------+----+-------------+------+-------+------+ | Id | User | Host | db | Command | Time | State | Info | +----+-------+-----------+----+-------------+------+-------+------+ | 6 | monty | localhost | | Processlist | 0 | | | +----+-------+-----------+----+-------------+------+-------+------+ Uptime: 10077 Threads: 1 Questions: 9 Slow queries: 0 Opens: 6 Flush tables: 1 Open tables: 2 Memory in use: 1092K Max memory used: 1116K
The mysqladmin status
command result has the following columns:
Column | Description |
Uptime | Number of seconds the MySQL server has been up. |
Threads | Number of active threads (clients). |
Questions | Number of questions from clients since mysqld was started.
|
Slow queries | Queries that have taken more than long_query_time seconds. See section 5.7.5 The Slow Query Log.
|
Opens | How many tables mysqld has opened.
|
Flush tables | Number of flush ... , refresh , and reload commands.
|
Open tables | Number of tables that are open now. |
Memory in use | Memory allocated directly by the mysqld code (only available when MySQL is compiled with --with-debug=full).
|
Max memory used | Maximum memory allocated directly by the mysqld code (only available when MySQL is compiled with --with-debug=full).
|
If you do mysqladmin shutdown
on a socket (in other words, on a
the computer where mysqld
is running), mysqladmin
will
wait until the MySQL pid-file
is removed to ensure that
the mysqld
server has stopped properly.
mysqlbinlog
, Executing the queries from a binary log
You can examine the binary log file (see section 5.7.4 The Binary Log) with the
mysqlbinlog
utility.
shell> mysqlbinlog hostname-bin.001
will print all queries contained in binlog `hostname-bin.001', together with information (time the query took, ID of the thread which issued it, timestamp when it was issued etc).
You can pipe the output of mysqlbinlog
into a mysql
client; this is used to recover from a crash when you have an old
backup (see section 5.5.1 Database Backups):
shell> mysqlbinlog hostname-bin.001 | mysql
or:
shell> mysqlbinlog hostname-bin.[0-9]* | mysql
You can also redirect the output of mysqlbinlog
to a text file
instead, modify this text file (to cut queries you don't want to
execute for some reason), then execute the queries from the text file
into mysql
.
mysqlbinlog
has the position=#
options which will print
only queries whose offset in the binlog is greater or equal to #
.
If you have more than one binary log to execute on the MySQL server, the safe method is to do it in one unique MySQL connection. Here is what may be UNsafe:
shell> mysqlbinlog hostname-bin.001 | mysql # DANGER!! shell> mysqlbinlog hostname-bin.002 | mysql # DANGER!!
It will cause problems if the first binlog contains a CREATE
TEMPORARY TABLE
and the second one contains a query which uses this
temporary table: when the first mysql
terminates, it will drop
the temporary table, so the second mysql
will report ``unknown
table''. This is why you should run all binlogs you want in one unique
connection, especially if you use temporary tables. Here are two
possible ways:
shell> mysqlbinlog hostname-bin.001 hostname-bin.002 | mysql
shell> mysqlbinlog hostname-bin.001 > /tmp/queries.sql shell> mysqlbinlog hostname-bin.002 >> /tmp/queries.sql shell> mysql -e "source /tmp/queries.sql"
Starting from MySQL 4.0.14, mysqlbinlog
can prepare suitable input
for mysql
to
execute a LOAD DATA INFILE
from a binlog. As the binlog
contains the data to load (this is true for MySQL 4.0; MySQL 3.23 did
not write the loaded data into the binlog, so the original
file was needed when one wanted to execute the content of
the binlog), mysqlbinlog
will copy this data to a
temporary file and print a LOAD DATA INFILE
command for
mysql
to load
this temporary file. The location where the temporary file is
created is by default the temporary directory; it can be changed with
the local-load
option of mysqlbinlog
.
Warning: When you run mysqlbinlog
on a binary log file,
it will create a temporary file for every found LOAD DATA INFILE
command. These files will not be automatically deleted, because
you will need them when executing the produced sql log. You should delete
them yourself when you don't need the sql log anymore. The files are named
`temporary-dir/original_file_name-#-#'.
In the future we will fix this problem by allowing mysqlbinlog
to connect directly to a mysqld
server. In this case we can
safely remove the log files when the logs have been applied.
Before MySQL 4.1, mysqlbinlog
could not prepare suitable output
for mysql
when the binary log contained queries from different
threads using temporary tables of the same name, if these queries were
interlaced. This is solved in MySQL 4.1.
You can also use mysqlbinlog --read-from-remote-server
to read
the binary log directly from a remote MySQL server. However, this is
something that is deprecated as we instead want to make it easy to to
apply binary logs to a running MySQL server.
mysqlbinlog --help
will give you more information.
mysqlcheck
for Table Maintenance and Crash Recovery
Since MySQL version 3.23.38 you will be able to use a new
checking and repairing tool for MyISAM
tables. The difference to
myisamchk
is that mysqlcheck
should be used when the
mysqld
server is running, whereas myisamchk
should be used
when it is not. The benefit is that you no longer have to take down the
server for checking or repairing your tables.
mysqlcheck
uses MySQL server commands CHECK
,
REPAIR
, ANALYZE
and OPTIMIZE
in a convenient way
for the user.
There are three alternative ways to invoke mysqlcheck
:
shell> mysqlcheck [OPTIONS] database [tables] shell> mysqlcheck [OPTIONS] --databases DB1 [DB2 DB3...] shell> mysqlcheck [OPTIONS] --all-databases
So it can be used in a similar way as mysqldump
when it
comes to what databases and tables you want to choose.
mysqlcheck
does have a special feature compared to the other
clients; the default behavior, checking tables (-c), can be changed by
renaming the binary. So if you want to have a tool that repairs tables
by default, you should just copy mysqlcheck
to your harddrive
with a new name, mysqlrepair
, or alternatively make a symbolic
link to mysqlrepair
and name the symbolic link as
mysqlrepair
. If you invoke mysqlrepair
now, it will repair
tables by default.
The names that you can use to change mysqlcheck
default behavior
are here:
mysqlrepair: The default option will be -r mysqlanalyze: The default option will be -a mysqloptimize: The default option will be -o
The options available for mysqlcheck
are listed here, please
check what your version supports with mysqlcheck --help
.
-A, --all-databases
-1, --all-in-1
-a, --analyze
--auto-repair
-#, --debug=...
--character-sets-dir=...
-c, --check
-C, --check-only-changed
--compress
-?, --help
-B, --databases
--default-character-set=...
-F, --fast
-f, --force
-e, --extended
-h, --host=...
-m, --medium-check
-o, --optimize
-p, --password[=...]
-P, --port=...
--protocol=(TCP | SOCKET | PIPE | MEMORY)
-q, --quick
-r, --repair
-s, --silent
-S, --socket=...
--tables
--databases
(-B
). All arguments
following that option are regarded as table names.
-u, --user=#
-v, --verbose
-V, --version
mysqldump
, Dumping Table Structure and Data
The mysqldump
client can be used
to dump a database or a collection of database for backup or for
transferring the data to another SQL server (not necessarily a MySQL
server). The dump will contain SQL statements to create the table
and/or populate the table.
If you are doing a backup on the server, you should consider using
the mysqlhotcopy
instead. See section 8.8 mysqlhotcopy
, Copying MySQL Databases and Tables.
shell> mysqldump [OPTIONS] database [tables] OR mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...] OR mysqldump [OPTIONS] --all-databases [OPTIONS]
If you don't give any tables or use the --databases
or
--all-databases
option, entire databases will be dumped.
You can get a list of the options your version of mysqldump
supports
by executing mysqldump --help
.
If you run mysqldump
without --quick
or
--opt
, mysqldump
will load the whole result set into
memory before dumping the result. This will probably be a problem if
you are dumping a big database.
If you are using a recent copy of the mysqldump
program
and you are going to do a dump that will be read into a very old MySQL
server, you should not use the --opt
or -e
options.
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 example 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.
mysqldump
supports the following options:
--add-locks
LOCK TABLES
before and UNLOCK TABLE
after each table dump.
(To get faster inserts into MySQL.)
--add-drop-table
drop table
before each create statement.
-A, --all-databases
--databases
with all
databases selected.
-a, --all
--allow-keywords
-c, --complete-insert
--comments=...
0
, suppresses additional information (like program version,
server version, host) in dumps. The --skip-comments
option does
the same. Default is 1
to not suppress that information.
New in MySQL 4.0.17.
-C, --compress
-B, --databases
USE db_name;
will be included in the output before each new database.
--default-character-set=...
utf8
, earlier versions use latin1
.
--delayed
INSERT DELAYED
command.
-e, --extended-insert
INSERT
syntax. (Gives more compact and
faster inserts statements.)
-#, --debug[=option_string]
--help
--fields-terminated-by=...
--fields-enclosed-by=...
--fields-optionally-enclosed-by=...
--fields-escaped-by=...
--lines-terminated-by=...
-T
option and have the same
meaning as the corresponding clauses for LOAD DATA INFILE
.
See section 13.1.5 LOAD DATA INFILE
Syntax.
-F, --flush-logs
--all-databases
(or -A
) option, the logs will be flushed
for each database dumped.
-f, --force
-h, --host=...
localhost
.
-l, --lock-tables
READ LOCAL
to allow concurrent inserts in the case of MyISAM
tables.
Please note that when dumping multiple databases, --lock-tables
will lock tables for each database separately. So using this option will
not guarantee your tables will be logically consistent between databases.
Tables in different databases may be dumped in completely different
states.
-K, --disable-keys
/*!40000 ALTER TABLE tb_name DISABLE KEYS */;
and
/*!40000 ALTER TABLE tb_name ENABLE KEYS */;
will be put in the output. This will make loading the data into a MySQL
4.0 server faster as the indexes are created after all data are inserted.
-n, --no-create-db
CREATE DATABASE /*!32312 IF NOT EXISTS*/ db_name;
will not be put in the
output. The above line will be added otherwise, if a --databases
or
--all-databases
option was given.
-t, --no-create-info
CREATE TABLE
statement).
-d, --no-data
--opt
--quick --add-drop-table --add-locks --extended-insert
--lock-tables
. Should give you the fastest possible dump for reading
into a MySQL server.
-pyour_pass, --password[=your_pass]
mysqldump
you will be prompted for a password.
-P, --port=...
--protocol=(TCP | SOCKET | PIPE | MEMORY)
-q, --quick
mysql_use_result()
to do this. Especially useful for big dumps.
-Q, --quote-names
-r, --result-file=...
--single-transaction
BEGIN
SQL command before dumping data from
server. It is mostly useful with InnoDB
tables and
READ_COMMITTED
transaction isolation level, as in this mode it
will dump the consistent state of the database at the time then
BEGIN
was issued without blocking any applications.
When using this option you should keep in mind that only transactional
tables will be dumped in a consistent state, for example, any MyISAM
or
HEAP
tables dumped while using this option may still change
state.
The --single-transaction
option was added in version 4.0.2.
This option is mutually exclusive with the --lock-tables
option
as LOCK TABLES
already commits a previous transaction internally.
-S /path/to/socket, --socket=/path/to/socket
localhost
(which is the
default host).
--skip-comments
--comments
to 0
. New in MySQL 4.0.17.
--tables
-T, --tab=path-to-some-directory
table_name.sql
file, that contains the SQL CREATE commands,
and a table_name.txt
file, that contains the data, for each give table.
The format of the `.txt' file is made according to the
--fields-xxx
and --lines--xxx
options.
Note: This option only works if mysqldump
is run on the same
machine as the mysqld
daemon. You must use a MySQL account that has the
FILE
privilege, and the login user/group that mysqld
is running as (normally user mysql
, group mysql
) must have
permission to create/write a file at the location you specify.
-u user_name, --user=user_name
-O name=value, --set-variable=name=value
--set-variable=name=value
and -O name=value
syntax is deprecated as of MySQL 4.0. Use --name=value
instead.
-v, --verbose
-V, --version
-w, --where='where-condition'
"--where=user='jimf'" "-wuserid>1" "-wuserid<1"
-X, --xml
-x, --first-slave
--master-data
--first-slave
, but also prints some CHANGE MASTER
TO
commands which will later make your slave start from the right position
in the master's binlogs, if you have set up your slave using this SQL
dump of the master.
-O net_buffer_length=#, where # < 16M
--extended-insert
or --opt
), mysqldump
will create
rows up to net_buffer_length
length. If you increase this
variable, you should also ensure that the max_allowed_packet
variable in the MySQL server is bigger than the
net_buffer_length
.
The most normal use of mysqldump
is probably for making a backup of
whole databases. See section 5.5.1 Database Backups.
mysqldump --opt database > backup-file.sql
You can read this back into MySQL with:
mysql database < backup-file.sql
or:
mysql -e "source /path-to-backup/backup-file.sql" database
However, it's also very useful to populate another MySQL server with information from a database:
mysqldump --opt database | mysql --host=remote-host -C database
It is possible to dump several databases with one command:
mysqldump --databases database1 [database2 ...] > my_databases.sql
If all the databases are wanted, one can use:
mysqldump --all-databases > all_databases.sql
mysqlhotcopy
, Copying MySQL Databases and Tables
mysqlhotcopy
is a Perl script that uses LOCK TABLES
,
FLUSH TABLES
and cp
or scp
to quickly make a backup
of a database. It's the fastest way to make a backup of the database
or single tables, but it can only be run on the same machine where the
database directories are. mysqlhotcopy
works only for backing up
MyISAM
and ISAM
tables. It runs on Unix, and on NetWare as of
MySQL 4.0.18.
mysqlhotcopy db_name [/path/to/new_directory] mysqlhotcopy db_name_1 ... db_name_n /path/to/new_directory mysqlhotcopy db_name./regex/
mysqlhotcopy
supports the following options:
-?, --help
-u, --user=#
-p, --password=#
-P, --port=#
-S, --socket=#
--allowold
--keepold
--noindices
myisamchk -rq.
.
--method=#
cp
or scp
).
-q, --quiet
--debug
-n, --dryrun
--regexp=#
--suffix=#
--checkpoint=#
--flushlog
--tmpdir=#
You can use perldoc mysqlhotcopy
to get more complete
documentation for mysqlhotcopy
.
mysqlhotcopy
reads the groups [client]
and [mysqlhotcopy]
from the option files.
To be able to execute mysqlhotcopy
you need write access to the
backup directory, the SELECT
privilege for the tables you are about to
copy and the MySQL RELOAD
privilege (to be able to
execute FLUSH TABLES
).
mysqlimport
, Importing Data from Text Files
mysqlimport
provides a command-line interface to the LOAD DATA
INFILE
SQL statement. Most options to mysqlimport
correspond
directly to the same options to LOAD DATA INFILE
.
See section 13.1.5 LOAD DATA INFILE
Syntax.
mysqlimport
is invoked like this:
shell> mysqlimport [options] database textfile1 [textfile2 ...]
For each text file named on the command-line,
mysqlimport
strips any extension from the filename and uses the result
to determine which table to import the file's contents into. For example,
files named `patient.txt', `patient.text', and `patient' would
all be imported into a table named patient
.
mysqlimport
supports the following options:
-c, --columns=...
LOAD DATA INFILE
command,
which is then passed to MySQL. See section 13.1.5 LOAD DATA INFILE
Syntax.
-C, --compress
-#, --debug[=option_string]
-d, --delete
--fields-terminated-by=...
--fields-enclosed-by=...
--fields-optionally-enclosed-by=...
--fields-escaped-by=...
--lines-terminated-by=...
LOAD DATA INFILE
. See section 13.1.5 LOAD DATA INFILE
Syntax.
-f, --force
--force
,
mysqlimport
exits if a table doesn't exist.
--help
-h host_name, --host=host_name
localhost
.
-i, --ignore
--replace
option.
--ignore-lines=n
n
lines of the datafile.
-l, --lock-tables
-L, --local
localhost
(which is the default host).
-pyour_pass, --password[=your_pass]
mysqlimport
you will be prompted for a password.
-P port_num, --port=port_num
--protocol=(TCP | SOCKET | PIPE | MEMORY)
-r, --replace
--replace
and --ignore
options control handling of input
records that duplicate existing records on unique key values. If you specify
--replace
, new rows replace existing rows that have the same unique key
value. If you specify --ignore
, input rows that duplicate an existing
row on a unique key value are skipped. If you don't specify either option, an
error occurs when a duplicate key value is found, and the rest of the text
file is ignored.
-s, --silent
-S /path/to/socket, --socket=/path/to/socket
localhost
(which is the
default host).
-u user_name, --user=user_name
-v, --verbose
-V, --version
Here is a sample run using mysqlimport
:
$ mysql --version mysql Ver 9.33 Distrib 3.22.25, for pc-linux-gnu (i686) $ uname -a Linux xxx.com 2.2.5-15 #1 Mon Apr 19 22:21:09 EDT 1999 i586 unknown $ mysql -e 'CREATE TABLE imptest(id INT, n VARCHAR(30))' test $ ed a 100 Max Sydow 101 Count Dracula . w imptest.txt 32 q $ od -c imptest.txt 0000000 1 0 0 \t M a x S y d o w \n 1 0 0000020 1 \t C o u n t D r a c u l a \n 0000040 $ mysqlimport --local test imptest.txt test.imptest: Records: 2 Deleted: 0 Skipped: 0 Warnings: 0 $ mysql -e 'SELECT * FROM imptest' test +------+---------------+ | id | n | +------+---------------+ | 100 | Max Sydow | | 101 | Count Dracula | +------+---------------+
mysqlshow
, Showing Databases, Tables, and Columns
mysqlshow
can be used to quickly look at which databases exist,
their tables, and the table's columns.
With the mysql
program you can get the same information with the
SHOW
commands. See section 13.5.3 SHOW
Syntax.
mysqlshow
is invoked like this:
shell> mysqlshow [OPTIONS] [database [table [column]]]
Note that in newer MySQL versions, you only see those database/tables/columns for which you have some privileges.
If the last argument contains a shell or SQL wildcard (*
,
?
, %
or _
) then only what's matched by the wildcard
is shown. If a database name contains any underscores, those should be escaped
with backslash (some Unix shells will require two), in order to get
tables / columns properly. '*' are converted into SQL '%' wildcard and
'?' into SQL '_' wildcard. This may cause some confusion when you try
to display the columns for a table with a _
as in this case
mysqlshow
only shows you the table names that match the pattern.
This is easily fixed by adding an extra %
last on the
command-line (as a separate argument).
myisampack
, The MySQL Compressed Read-only Table Generator
myisampack
is used to compress MyISAM tables, and pack_isam
is used to compress ISAM tables. Because ISAM tables are deprecated, we
will only discuss myisampack
here, but everything said about
myisampack
should also be true for pack_isam
.
myisampack
works by compressing each column in the table separately.
The information needed to decompress columns is read into memory when the
table is opened. This results in much better performance when accessing
individual records, because you only have to uncompress exactly one record, not
a much larger disk block as when using Stacker on MS-DOS.
Usually, myisampack
packs the datafile 40%-70%.
MySQL uses memory mapping (mmap()
) on compressed tables and
falls back to normal read/write file usage if mmap()
doesn't work.
Please note the following:
myisampack
can also pack BLOB
or TEXT
columns.
The older pack_isam
(for ISAM
tables) cannot do this.
myisampack
is invoked like this:
shell> myisampack [options] filename ...
Each filename should be the name of an index (`.MYI') file. If you are not in the database directory, you should specify the pathname to the file. It is permissible to omit the `.MYI' extension.
myisampack
supports the following options:
-b, --backup
tbl_name.OLD
.
-#, --debug=debug_options
debug_options
string often is
'd:t:o,filename'
.
-f, --force
myisampack
creates a temporary file named `tbl_name.TMD'
while it compresses the table. If you kill myisampack
, the `.TMD'
file may not be deleted. Normally, myisampack
exits with an error if
it finds that `tbl_name.TMD' exists. With --force
,
myisampack
packs the table anyway.
-?, --help
-j big_tbl_name, --join=big_tbl_name
big_tbl_name
. All tables that are to be combined
must be identical (same column names and types, same indexes, etc.).
-p #, --packlength=#
myisampack
stores all rows with length pointers of 1, 2, or 3
bytes. In most normal cases, myisampack
can determine the right length
value before it begins packing the file, but it may notice during the packing
process that it could have used a shorter length. In this case,
myisampack
will print a note that the next time you pack the same file,
you could use a shorter record length.)
-s, --silent
-t, --test
-T dir_name, --tmp_dir=dir_name
-v, --verbose
-V, --version
-w, --wait
mysqld
server was
invoked with the --skip-external-locking
option, it is not a good idea
to invoke myisampack
if the table might be updated during the
packing process.
The sequence of commands shown here illustrates a typical table compression session:
shell> ls -l station.* -rw-rw-r-- 1 monty my 994128 Apr 17 19:00 station.MYD -rw-rw-r-- 1 monty my 53248 Apr 17 19:00 station.MYI -rw-rw-r-- 1 monty my 5767 Apr 17 19:00 station.frm shell> myisamchk -dvv station MyISAM file: station Isam-version: 2 Creation time: 1996-03-13 10:08:58 Recover time: 1997-02-02 3:06:43 Data records: 1192 Deleted blocks: 0 Datafile: Parts: 1192 Deleted data: 0 Datafile pointer (bytes): 2 Keyfile pointer (bytes): 2 Max datafile length: 54657023 Max keyfile length: 33554431 Recordlength: 834 Record format: Fixed length table description: Key Start Len Index Type Root Blocksize Rec/key 1 2 4 unique unsigned long 1024 1024 1 2 32 30 multip. text 10240 1024 1 Field Start Length Type 1 1 1 2 2 4 3 6 4 4 10 1 5 11 20 6 31 1 7 32 30 8 62 35 9 97 35 10 132 35 11 167 4 12 171 16 13 187 35 14 222 4 15 226 16 16 242 20 17 262 20 18 282 20 19 302 30 20 332 4 21 336 4 22 340 1 23 341 8 24 349 8 25 357 8 26 365 2 27 367 2 28 369 4 29 373 4 30 377 1 31 378 2 32 380 8 33 388 4 34 392 4 35 396 4 36 400 4 37 404 1 38 405 4 39 409 4 40 413 4 41 417 4 42 421 4 43 425 4 44 429 20 45 449 30 46 479 1 47 480 1 48 481 79 49 560 79 50 639 79 51 718 79 52 797 8 53 805 1 54 806 1 55 807 20 56 827 4 57 831 4 shell> myisampack station.MYI Compressing station.MYI: (1192 records) - Calculating statistics normal: 20 empty-space: 16 empty-zero: 12 empty-fill: 11 pre-space: 0 end-space: 12 table-lookups: 5 zero: 7 Original trees: 57 After join: 17 - Compressing file 87.14% shell> ls -l station.* -rw-rw-r-- 1 monty my 127874 Apr 17 19:00 station.MYD -rw-rw-r-- 1 monty my 55296 Apr 17 19:04 station.MYI -rw-rw-r-- 1 monty my 5767 Apr 17 19:00 station.frm shell> myisamchk -dvv station MyISAM file: station Isam-version: 2 Creation time: 1996-03-13 10:08:58 Recover time: 1997-04-17 19:04:26 Data records: 1192 Deleted blocks: 0 Datafile: Parts: 1192 Deleted data: 0 Datafilepointer (bytes): 3 Keyfile pointer (bytes): 1 Max datafile length: 16777215 Max keyfile length: 131071 Recordlength: 834 Record format: Compressed table description: Key Start Len Index Type Root Blocksize Rec/key 1 2 4 unique unsigned long 10240 1024 1 2 32 30 multip. text 54272 1024 1 Field Start Length Type Huff tree Bits 1 1 1 constant 1 0 2 2 4 zerofill(1) 2 9 3 6 4 no zeros, zerofill(1) 2 9 4 10 1 3 9 5 11 20 table-lookup 4 0 6 31 1 3 9 7 32 30 no endspace, not_always 5 9 8 62 35 no endspace, not_always, no empty 6 9 9 97 35 no empty 7 9 10 132 35 no endspace, not_always, no empty 6 9 11 167 4 zerofill(1) 2 9 12 171 16 no endspace, not_always, no empty 5 9 13 187 35 no endspace, not_always, no empty 6 9 14 222 4 zerofill(1) 2 9 15 226 16 no endspace, not_always, no empty 5 9 16 242 20 no endspace, not_always 8 9 17 262 20 no endspace, no empty 8 9 18 282 20 no endspace, no empty 5 9 19 302 30 no endspace, no empty 6 9 20 332 4 always zero 2 9 21 336 4 always zero 2 9 22 340 1 3 9 23 341 8 table-lookup 9 0 24 349 8 table-lookup 10 0 25 357 8 always zero 2 9 26 365 2 2 9 27 367 2 no zeros, zerofill(1) 2 9 28 369 4 no zeros, zerofill(1) 2 9 29 373 4 table-lookup 11 0 30 377 1 3 9 31 378 2 no zeros, zerofill(1) 2 9 32 380 8 no zeros 2 9 33 388 4 always zero 2 9 34 392 4 table-lookup 12 0 35 396 4 no zeros, zerofill(1) 13 9 36 400 4 no zeros, zerofill(1) 2 9 37 404 1 2 9 38 405 4 no zeros 2 9 39 409 4 always zero 2 9 40 413 4 no zeros 2 9 41 417 4 always zero 2 9 42 421 4 no zeros 2 9 43 425 4 always zero 2 9 44 429 20 no empty 3 9 45 449 30 no empty 3 9 46 479 1 14 4 47 480 1 14 4 48 481 79 no endspace, no empty 15 9 49 560 79 no empty 2 9 50 639 79 no empty 2 9 51 718 79 no endspace 16 9 52 797 8 no empty 2 9 53 805 1 17 1 54 806 1 3 9 55 807 20 no empty 3 9 56 827 4 no zeros, zerofill(2) 2 9 57 831 4 no zeros, zerofill(1) 2 9
The information printed by myisampack
is described here:
normal
empty-space
empty-zero
empty-fill
INTEGER
column may be changed to MEDIUMINT
).
pre-space
end-space
table-lookup
ENUM
before Huffman compression.
zero
Original trees
After join
After a table has been compressed, myisamchk -dvv
prints additional
information about each field:
Type
constant
no endspace
no endspace, not_always
no endspace, no empty
table-lookup
ENUM
.
zerofill(n)
n
bytes in the value are always 0 and are not
stored.
no zeros
always zero
Huff tree
Bits
After you have run pack_isam
/myisampack
you must run
isamchk
/myisamchk
to re-create the index. At this time you
can also sort the index blocks and create statistics needed for
the MySQL optimizer to work more efficiently:
myisamchk -rq --analyze --sort-index table_name.MYI isamchk -rq --analyze --sort-index table_name.ISM
After you have installed the packed table into the MySQL database
directory you should do mysqladmin flush-tables
to force mysqld
to start using the new table.
If you want to unpack a packed table, you can do this with the
--unpack
option to isamchk
or myisamchk
.
mysql_config
, Get compile options for compiling clients
mysql_config
provides you with useful information how to compile
your MySQL client and connect it to MySQL.
mysql_config
supports the following options:
--cflags
libmysqlclient
library.
--include
--cflags
instead of this)
--libs
--libs_r
--socket
--port
--version
--libmysqld-libs or --embedded
If you execute mysql_config
without any options it will print
all options it supports plus the value of all options:
shell> mysql_config Usage: /usr/local/mysql/bin/mysql_config [OPTIONS] Options: --cflags [-I/usr/local/mysql/include/mysql -mcpu=pentiumpro] --include [-I/usr/local/mysql/include/mysql] --libs [-L/usr/local/mysql/lib/mysql -lmysqlclient -lz -lcrypt -lnsl -lm -L/usr/lib -lssl -lcrypto] --libs_r [-L/usr/local/mysql/lib/mysql -lmysqlclient_r -lpthread -lz -lcrypt -lnsl -lm -lpthread] --socket [/tmp/mysql.sock] --port [3306] --version [4.0.16] --libmysqld-libs [-L/usr/local/mysql/lib/mysql -lmysqld -lpthread -lz -lcrypt -lnsl -lm -lpthread -lrt]
You can use this to compile a MySQL client by as follows:
CFG=/usr/local/mysql/bin/mysql_config sh -c "gcc -o progname `$CFG --cflags` progname.c `$CFG --libs`"
perror
, Explaining Error Codes
For most system errors MySQL will, in addition to a internal text message,
also print the system error code in one of the following styles:
message ... (errno: #)
or message ... (Errcode: #)
.
You can find out what the error code means by either examining the
documentation for your system or use the perror
utility.
perror
prints a description for a system error code, or an MyISAM/ISAM
storage engine (table handler) error code.
perror
is invoked like this:
shell> perror [OPTIONS] [ERRORCODE [ERRORCODE...]] Example: shell> perror 13 64 Error code 13: Permission denied Error code 64: Machine is not on the network
Note that the error messages are mostly system dependent!
Go to the first, previous, next, last section, table of contents.