Go to the first, previous, next, last section, table of contents.


15 MySQL ユーティリティ

In this chapter you will learn about the MySQL Utilities that come in a given distribution. You will learn what each of them does, how to use it, and what you should use it for.

15.1 様々な MySQL プログラムの概要

サーバと通信する mysqlclient ライブラリを使用している全ての MySQL クライアントは次の環境変数を使用します:

Name Description
MYSQL_UNIX_PORT デフォルトのソケット; localhost への接続に使用される
MYSQL_TCP_PORT デフォルトの TCP/IP ポート
MYSQL_PWD デフォルトのパスワード
MYSQL_DEBUG デバッグオプション
TMPDIR 一時 tables/files が作成されるディレクトリ

MYSQL_PWD の使用は安全ではありません。 「6.6 MySQL サーバーに接続」節参照.

`mysql' クライアントは、MYSQL_HISTFILE 環境変数に 指定されているファイルにコマンドラインの履歴を書き出します。 デフォルトの履歴ファイルは、 `$HOME/.mysql_history' で、$HOMEHOME 環境変数の値です。 「A Environment Variables」節参照.

全ての MySQL プログラムは多くの様々なオプションを持ちます。種々 のオプションの完全な説明を得るにはスイッチ --help を使用してください。例 えばmysql --help を試してください。

オプションファイルで、全ての標準クライアントのデフォルトのオプションを 変更することが可能です。 「4.16.5 オプションファイル ( my.cnf )」節.

MySQL プログラムを以下に示します:

myisamchk
MySQL テーブルをチェック, 最適化そして修復します。 myisamchk には多くの機能があるので、一章割り当てて説明しています。 「16 Maintaining a MySQL Installation」節参照.
make_binary_distribution
コンパイルされた MySQL のバイナリリリースを作成します。これは他 の MySQL ユーザの利便のために、ftp で support.mysql.com`/pub/mysql/Incoming' に送ることができます。
msql2mysql
mSQL プログラムを MySQL に変換するシェルスクリプト。全て のケースで処理できるわけではありませんが、変換時に良いスタートを与えます。
mysql
mysql は簡単な SQL シェル (GNU readline つき) です。これは対話的な使用や 非対話型問い合わせをサポートします。対話的に使用されると、ASCII テーブル 形式で結果が与えられます。フィルタとして使用されると、出力はタブで区切ら れます(これは起動時のオプションで他のものに変更できます)。 あなたは以下のように簡単にスクリプトを実行できます:
shell> mysql database < script.sql > output.tab
クライアントのメモリが十分でないことによる問題がある場合は、 --quick スイッチを使用してください! これは結果を取り出すのに mysql_store_result() の代わりに mysql_use_result() を使用 するように mysql に強制させます。
mysqlaccess
ホスト, ユーザそしてデータベースの組合せで権限をチェックするためのスクリ プト。
mysqladmin
管理ユーティリティ。データベースの作成/破棄。reload (新しいユーザの読み 込み) と refresh (ディスクへのテーブルのフラッシュ, ログファイルの再オー プン)。サーバのバージョンと処理と状態情報も与えます。 「15.6 MySQL サーバーの管理 ( mysqladmin )」節参照.
mysqlbug
MySQL バグレポートスクリプト。 このスクリプトは MySQL メーリングリストにバグレポートを出す際、 常に使用します。
mysqld
SQL デーモン。これは常に実行されてます。
mysqldump
MySQL データベースの SQL ステートメントまたはタブで区切られたテ キストのファイルにダンプします。Igor Romanenko によって独創的にエンハン スされたフリーウェア。 「15.7 MySQL データベースとテーブルから、構造とデータをダンプ ( mysqldump )」節参照.
mysqlimport
一つまたは複数のテキストファイルをそれぞれのテーブルに読み込みます。LOAD DATA INFILE でサポートされる全ての形式を使用できます。 「15.9 テキストファイルからデータを取り込む ( mysqlimport )」節参照.
mysqlshow
データベース, テーブル, 項目そしてインデックスについての情報を表示します。
mysql_install_db
MySQL 承認テーブルをデフォルトの権限で作成します。これは通常、最 初の MySQL リリースを新しいシステム上にインストールする時に一回 だけ実行されます。
replace
msql2mysql で使用されるバイナリ。ファイル内または標準入力上の文字列を変 換するユーティリティプログラム。より長い文字列に最初に適合するため有限状 態マシンを使用します。文字列を交換するために使用できます。例えば、 ab を与えられたファイル内で交換します:
shell> replace a b b a -- file1 file2 ...

15.2 mysqld-max, An extended mysqld server

mysqld-max is the MySQL server (mysqld) configured with the following configure options:

Option Comment
--with-server-suffix=-Max Add a suffix to the mysqld version string.
--with-bdb Support for Berkeley DB (BDB) tables
--with-innodb Support for InnoDB tables.
CFLAGS=-DUSE_SYMDIR Symbolic links support for Windows.

Note that as Berkeley DB and InnoDB are not available for all platforms, some of the Max binaries may not have support for both of these. You can check which table types are supported by doing the following query:

mysql> show variables like "have_%";
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| have_bdb      | YES   |
| have_gemini   | NO    |
| have_innodb   | NO    |
| have_isam     | YES   |
| have_raid     | YES   |
| have_ssl      | NO    |
+---------------+-------+

The meaning of the values are:

Value Meaning.
YES The option is activated and usable.
NO MySQL is not compiled with support for this option.
DISABLED The xxxx option is disabled because one started mysqld with --skip-xxxx or because one didn't start mysqld with all needed options to enable the option. In this case the hostname.err file should contain a reason for why the option is disabled.

NOTE: To be able to create InnoDB tables you MUST edit your startup options to include at least the innodb_data_file_path option. 「8.7.2 InnoDB startup options」節参照.

To get better performance for BDB tables, you should add some configuration options for these too. 「8.5.3 BDB startup options」節参照.

safe_mysqld will automaticly try to start any mysqld binary with the -max prefix. This makes it very easy to test out a another mysqld binary in an existing installation. Just run configure with the options you want and then install the new mysqld binary as mysqld-max in the same directory where your old mysqld binary is. 「15.3 safe_mysqld, the wrapper around mysqld」節参照.

The mysqld-max RPM uses the above mentioned safe_mysqld feature. It just installs the mysqld-max executable and safe_mysqld will automaticly use this executable when safe_mysqld is restarted.

The following table shows which table types our standard MySQL-Max binaries includes:

System BDB InnoDB
AIX 4.3 N Y
HPUX 11.0 N Y
Linux-Alpha N Y
Linux-Intel Y Y
Linux-Ia64 N Y
Solaris-intel N Y
Solaris-sparc Y Y
SCO OSR5 Y Y
UnixWare Y Y

15.3 safe_mysqld, the wrapper around mysqld

safe_mysqld is the recommended way to start a mysqld daemon on UNIX. safe_mysqld adds some safety features such as restarting the server when an error occurs and logging runtime information to a log file.

If you don't use --mysqld=# or --mysqld-version=# safe_mysqld will use an executable named mysqld-max if it exists. If not, safe_mysqld will start mysqld. This makes it very easy to test to use mysqld-max instead of mysqld; Just copy mysqld-max to where you have mysqld and it will be used.

Normally one should never edit the safe_mysqld script, but instead put the options to safe_mysqld in the [safe_mysqld] section in the my.cnf file. safe_mysqld will read all options from the [mysqld], [server] and [safe_mysqld] sections from the option files. 「4.16.5 オプションファイル ( my.cnf )」節参照.

Note that all options on the command line to safe_mysqld are passed to mysqld. If you wants to use any options in safe_mysqld that mysqld doesn't support, you must specify these in the option file.

Most of the options to safe_mysqld are the same as the options to mysqld. 「4.16.4 mysqld コマンド行オプション」節参照.

safe_mysqld supports the following options:

--basedir=path
--core-file-size=#
Size of the core file mysqld should be able to create. Passed to ulimit -c.
--datadir=path
--defaults-extra-file=path
--defaults-file=path
--err-log=path
--ledir=path
Path to mysqld
--log=path
--mysqld=mysqld-version
Name of the mysqld version in the ledir directory you want to start.
--mysqld-version=version
Similar to --mysqld= but here you only give the suffix for mysqld. For example if you use --mysqld-version=max, safe_mysqld will start the ledir/mysqld-max version. If the argument to --mysqld-version is empty, ledir/mysqld will be used.
--no-defaults
--open-files-limit=#
Number of files mysqld should be able to open. Passed to ulimit -n. Note that you need to start safe_mysqld as root for this to work properly!
--pid-file=path
--port=#
--socket=path
--timezone=#
Set the timezone (the TZ) variable to the value of this parameter.
--user=#

The safe_mysqld script is written so that it normally is able to start a server that was installed from either a source or a binary version of MySQL, even if these install the server in slightly different locations. safe_mysqld expects one of these conditions to be true:

Because safe_mysqld will try 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 start safe_mysqld from the MySQL installation directory:

shell> cd mysql_installation_directory
shell> bin/safe_mysqld &

If safe_mysqld fails, even when invoked from the MySQL installation directory, you can modify it to use the path to mysqld and the pathname options that are correct for your system. Note that if you upgrade MySQL in the future, your modified version of safe_mysqld will be overwritten, so you should make a copy of your edited version that you can reinstall.

15.4 mysqld_multi, program for managing multiple MySQL servers

mysqld_multi is meant for managing several mysqld processes running in different UNIX sockets and TCP/IP ports.

The program will search for group(s) named [mysqld#] from my.cnf (or the given --config-file=...), where # can be any positive number starting from 1. These groups should be the same as the usual [mysqld] group (e.g. options to mysqld, see MySQL manual for detailed information about this group), but with those port, socket etc. options that are wanted for each separate mysqld processes. The number in the group name has another function; it can be used for starting, stopping, or reporting some specific mysqld servers with this program. See the usage and options below for more information.

Usage: mysqld_multi [OPTIONS] {start|stop|report} [GNR,GNR,GNR...]
or     mysqld_multi [OPTIONS] {start|stop|report} [GNR-GNR,GNR,GNR-GNR,...]

The GNR above means the group number. You can start, stop or report any GNR, or several of them at the same time. (See --example) The GNRs list can be comma separated, or a dash combined, of which the latter + means that all the GNRs between GNR1-GNR2 will be affected. Without GNR argument all the found groups will be either started, stopped, or reported. Note that you must not have any white spaces in the GNR list. Anything after a white space is ignored.

mysqld_multi supports the following options:

--config-file=...
Alternative config file. NOTE: This will not affect this program's own options (group [mysqld_multi]), but only groups [mysqld#]. Without this option everything will be searched from the ordinary my.cnf file.
--example
Give an example of a config file.
--help
Print this help and exit.
--log=...
Log file. Full path to and the name for the log file. NOTE: If the file exists, everything will be appended.
--mysqladmin=...
mysqladmin binary to be used for a server shutdown.
--mysqld=...
mysqld binary to be used. Note that you can give safe_mysqld to this option also. The options are passed to mysqld. Just make sure you have mysqld in your environment variable PATH or fix safe_mysqld.
--no-log
Print to stdout instead of the log file. By default the log file is turned on.
--password=...
Password for user for mysqladmin.
--tcp-ip
Connect to the MySQL server(s) via the TCP/IP port instead of the UNIX socket. This affects stopping and reporting. If a socket file is missing, the server may still be running, but can be accessed only via the TCP/IP port. By default connecting is done via the UNIX socket.
--user=...
MySQL user for mysqladmin.
--version
Print the version number and exit.

Some notes about mysqld_multi:

22.3 同一マシン上に複数の MySQL サーバーを走らせる」節参照.

This is an example of the config file on behalf of mysqld_multi.

# 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/safe_mysqld
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.16.5 オプションファイル ( my.cnf )」節参照.

15.5 コマンドラインツール ( mysql

mysql はシンプルな SQL shell です(GNU readline を持っています). これは対話モードと、非対話モードを持っています。 対話モードで使用された場合、 クエリの結果は ASCII テーブルのフォーマットで与えられます。 非対話モードで使用された場合(例えばフィルターとして)、結果はタブ区切りの フォーマットで返ります。 (出力フォーマットはコマンドラインのオプションで変更できます) 以下のようにしてスクリプトを実行できます:

shell> mysql database < script.sql > output.tab

もしクライアントでメモリー不足の問題が出た場合、--quick オプションを 使用します! これは mysql に、結果セットを取得する際に、 mysql_store_result() ではなく mysql_use_result() を 使用させます。

mysql の使用はとても簡単です: mysql databasemysql --user=user_name --password=your_password d atabase のようにしてはじめます。 SQL 文を入力し、一文を `;', `\g' or `\G' で終え、 RETURN/ENTER を押します。

mysql は以下のオプションをサポートします:

-?, --help
help を表示して終了
-A, --no-auto-rehash
自動リハッシュをしない。 テーブルとフィールドの取得には 'rehash' を使用しなくては なりません。 これは mysql の起動を速くします。
-B, --batch
結果をタブ区切り、1レコードは1行で出力します。 history ファイルは使用しません。
--character-sets-dir=...
Directory where character sets are located.
-C, --compress
サーバー・クライアント間の通信を圧縮します
-#, --debug[=...]
デバッグログ。 デフォルトは 'd:t:o,/tmp/mysql.trace'
-D, --database=..
使用するデータベース。 これは my.cnf ファイルが便利です
--default-character-set=...
Set the default character set.
-e, --execute=...
コマンドを実行して終了。 (Output like with --batch)
-E, --vertical
垂直にレコードを出力します。 このオプションを指定していなくても、 SQL 文を \G で終了した場合、同じように垂直に出力します。
-f, --force
SQL エラーがおきたとしても、処理を続けます
-g, --no-named-commands
Named commands are disabled. Use \* form only, or use named commands only in the beginning of a line ending with a semicolon (;). Since Version 10.9, the client now starts with this option ENABLED by default! With the -g option, long format commands will still work from the first line, however.
-G, --enable-named-commands
Named commands are enabled. Long format commands are allowed as well as shortened \* commands.
-i, --ignore-space
関数名の後ろについたスペースを無視します
-h, --host=...
指定したホストに接続します
-H, --html
結果を HTML フォーマットで返します
-L, --skip-line-numbers
エラーの起きた行の番号を書きません。 これはエラーメッセージを含んだ結果を 比較する場合に便利です。
--no-pager
Disable pager and print to stdout. See interactive help (\h) also.
--no-tee
Disable outfile. See interactive help (\h) also.
-n, --unbuffered
それぞれのクエリ毎にバッファをフラッシュします
-N, --skip-column-names
結果に、フィールド名を書き出しません。
-O, --set-variable var=option
変数に値をセットします。 --help lists variables
-o, --one-database
デフォルトのデータベースのみ更新します。 これは update ログファイルを 使用して更新する場合、他のデータベースの更新を避けたい時に便利です。
--pager[=...]
Output type. Default is your 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[=...]
サーバーに接続する際のパスワード。 もしパスワードがコマンドラインに 指定されていなかった場合、tty 上でパスワードが問い合わされます。 -p を使用する場合、このオプションとパスワードの間には スペースが不要だということに注意してください。
-P --port=...
接続に使用する TCP/IP ポート番号
-q, --quick
結果をキャッシュせず、一レコードづつ出力します。 これはもし出力を中止した場合、サーバーを遅くします。 ヒストリファイルは使用しません。
-r, --raw
エスケープ処理をしないで値を書き出します。 --batch とともに使用されます
-s, --silent
静粛モード
-S --socket=...
接続に使用する ソケットファイル
-t --table
表の形式で出力します。 これは batch モード以外でのデフォルトです。
-T, --debug-info
Print some debug information at exit.
--tee=...
Append everything into outfile. See interactive help (\h) also. Does not work in batch mode.
-u, --user=#
ログインユーザー名
-U, --safe-updates[=#], --i-am-a-dummy[=#]
キーを使用する UPDATE and DELETE のみを行います。 これは後述します。 このオプションをもし my.cnf に書いている場合は、 --safe-updates=0 でこのオプションをリセットできます。
-v, --verbose
冗長出力。 (-v -v -v は表形式の出力を与える)
-V, --version
バージョンを表示して終了
-w, --wait
もし接続が落ちた場合、中断しないで、待って、再試行します。

You can also set the following variables with -O or --set-variable:

Variablename Default Description
connect_timeout 0 Number of seconds before timeout connection.
max_allowed_packet 16777216 Max packetlength to send/receive from to server
net_buffer_length 16384 Buffer for TCP/IP and socket communication
select_limit 1000 Automatic limit for SELECT when using --i-am-a-dummy
max_join_size 1000000 Automatic limit for rows in a join when using --i-am-a-dummy.

もしコマンドラインで 'help' と打った場合、mysql はサポートする コマンドを表示します:

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.
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.
quit    (\q)    Quit mysql.
rehash  (\#)    Rebuild completion hash.
source  (\.)    Execute a SQL script file. Takes a file name as an argument.
status  (\s)    Get status information from the server.
tee     (\T)    Set outfile [to_outfile]. Append everything into given outfile.
use     (\u)    Use another database. Takes database name as argument.

From the above, pager only works in UNIX.

status コマンドは、今使用している 接続とサーバーについての情報をいくつか表示します。 もし --safe-updates モードで使用している場合、 status は あなたのクエリに影響する mysql 変数の値を表示します。

初心者に便利な起動オプション(MySQL バージョン 3.23.11 で導入されました)は、 --safe-updates あるいは --i-am-a-dummy です。 ( これは DELETE FROM table_nameWHERE 節を忘れて 実行しようとした場合のためにあります。) このオプションが使用されると、 mysql は接続時に MySQL サーバーに 以下のようなコマンドを送ります:

SET SQL_SAFE_UPDATES=1,SQL_SELECT_LIMIT=#select_limit#,
    SQL_MAX_JOIN_SIZE=#max_join_size#"

ここで #select_limit##max_join_size# は変数で これらは mysql コマンドからセット可能です。 「7.33 SET 構文」節参照.

この効果は:

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)

15.6 MySQL サーバーの管理 ( mysqladmin )

管理オペレーションを実行するためのユーティリティ。シンタックスは:

shell> mysqladmin [OPTIONS] command [command-option] command ...

mysqladmin --help によって、オプションの一覧を手にいれることができます。

現在の mysqladmin は以下のコマンドをサポートします:

create databasename データベースの作成
drop databasename データベースとテーブルの全削除。
extended-status サーバーから拡張ステータスを取得。
flush-hosts キャッシュされている全ホストをフラッシュ。
flush-logs 全てのログをフラッシュ
flush-tables 全てのテーブルをフラッシュ
flush-privileges 許可テーブルの再読み込み (reload と同じ)
kill id,id,... mysql スレッドの kill.
password New-password 古いパスワードを New-password に変更
ping mysqld が生きているかチェック
processlist 現在活動中の mysql スレッドを表示
reload 許可テーブルの再読み込み
refresh 全テーブルをフラッシュし、ログファイルを一度閉じて開きます。
shutdown サーバーをダウンさせます。
slave-start Start slave replication thread
slave-stop Stop slave replication thread
status サーバーから短いステータスを得ます。
variables 変数の表示
version サーバーからバージョンを得ます。

全てのコマンドは、ユニークなプレフィックスで省略可能です。 例えば:

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

mysqladmin status コマンドの結果は、以下の項目を持ちます:

Uptime MySQL サーバーの起動秒数
Threads 稼働中のスレッド数 (clients)
Questions mysqld が開始してからのクライアントからのクエリ数
Slow queries long_query_time 秒より時間のかかったクエリの数 「23.5 The Slow Query Log」節参照.
Opens mysqld が開いたテーブル数
Flush tables flush ..., refresh, and reload コマンドの実行回数
Open tables 現在開かれているテーブルの数
Memory in use mysqld のコードによって直接割り当てられたメモリ (only available when MySQL is compiled with --with-debug=full)
Max memory used mysqld のコードによって直接割り当てられる最大メモリー量 (only available when MySQL is compiled with --with-debug=full)

If you do myslqadmin 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.

15.7 MySQL データベースとテーブルから、構造とデータをダンプ ( mysqldump )

データベース、あるいは、バックアップ、他のSQLサーバー(MySQL サーバである必 要はない)へのデータを移動を目的としたデータのまとまり、これらをダンプする ためのユーティリティ。ダンプは、テーブルの作成のための SQL 文を含みます。

サーバでバックアップを行なう場合、mysqlhotcopy を代わりに使用するこ とを考慮すべきです。 「15.8 Copying MySQL Databases and Tables」節参照。

shell> mysqldump [OPTIONS] database [tables]
OR     mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]
OR     mysqldump [OPTIONS] --all-databases [OPTIONS]

もしテーブルを指定せず、--databases--all-databases を 使用しなかったなら、データベースの全てのテーブルがダンプされます。

mysqldump --help によって、オプションの一覧を手にいれることができます。

もし mysqldump--quick--opt なしで実行するならば、 mysqldump は結果を表示する前に、結果をメモリに全てロードすることに 注意してください。 これは大きなデータベースをダンプする際に問題になるでしょう。

Note that if you are using a new 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.

mysqldump は以下のオプションをサポートします:

--add-locks
テーブルのダンプの前に LOCK TABLES 文を追加し、 テーブルのダンプ後に UNLOCK TABLE 文を追加します。 ( あとで MySQL に挿入するときにこれは速くなります ).
--add-drop-table
テーブルの create 文の前に、drop table 文を追加します。
-A, --all-databases
Dump all the databases. This will be same as --databases with all databases selected.
-a, --all
Include all MySQL specific create options.
--allow-keywords
キーワード(予約語) と同じ名前をもつフィールドの作成を許します。 これは、それぞれのフィールドの前に、テーブル名を付け足します。
-c, --complete-insert
完全な INSERT 文(フィールド名を書いた文) を使用します。
-C, --compress
もしサーバーとクライアントの双方が圧縮をサポートしているならば、 両者の間で行われる通信を全て圧縮します。
-B, --databases
To dump several databases. Note the difference in usage. In this case no tables are given. All name arguments are regarded as database names. USE db_name; will be included in the output before each new database.
--delayed
INSERT DELAYED コマンドを使用してレコードを INSERT します。
-e, --extended-insert
新しいマルチライン INSERT 構文を使用します。(これはあとで挿入する際、 よりコンパクトかつ速くなります。)
-#, --debug[=option_string]
Trace usage of the program (for debugging).
--help
Display a help message and exit.
--fields-terminated-by=...
--fields-enclosed-by=...
--fields-optionally-enclosed-by=...
--fields-escaped-by=...
--lines-terminated-by=...
これらのオプションは -T とともに使用され、 LOAD DATA INFILE と同様の意味をなします。 「7.23 LOAD DATA INFILE構文」節参照.
-F, --flush-logs
ダンプする前に、 MySQL サーバーのログファイルをフラッシュします。
-f, --force,
ダンプの途中で SQL エラーが発生しても、ダンプを続けます。
-h, --host=..
指定されたホストの MySQL サーバーからダンプします。 デフォルトのホストは localhost.
-l, --lock-tables.
ダンプを開始するとき全てのテーブルをロックします。 The tables are locked with READ LOCAL to allow concurrent inserts in the case of MyISAM tables.
-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 --databases or --all-databases option was given.
-t, --no-create-info
テーブルの作成情報( CREATE TABLE 文) を書き出しません。
-d, --no-data
テーブル内のレコードを書き出しません。 これはテーブルの構造だけを取り出したいときにとても便利です!
--opt
--quick --add-drop-table --add-locks --extended-insert --lock-tables と同じ. MySQL サーバーから読み出す時間を最短にしてくれます。
-pyour_pass, --password[=your_pass]
サーバーに接続する際のパスワードを与えます。 もし `=your_pass' 部分を与えなかった場合は、 mysqldump はパスワードのプロンプトをだします。
-P port_num, --port=port_num
サーバーに接続する際に使用する TCP/IP ポート番号。 (これは localhost 以外のホストへの接続に使用されます。 localhost の場合は、UNIX ソケットが使用されます。)
-q, --quick
クエリをバッファにため込みません。stdout に直接出します。 mysql_use_result() をこれに使用しています。
-r, --result-file=...
Direct output to a given file. This option should be used in MSDOS, because it prevents new line '\n' from being converted to '\n\r' (new line + carriage return).
-S /path/to/socket, --socket=/path/to/socket
localhost に接続する際のソケットファイルの指定 (デフォルトは /tmp/mysql.sock )
--tables
Overrides option --databases (-B).
-T, --tab=path-to-some-directory
与えられたテーブル毎に、 SQL CREATE 文を含む table_name.sql ファイル、 データを含む table_name.txt ファイルを作成します。 NOTE: これは mysqld デーモンが走っているマシン上で mysqldump を 実行する場合にだけ、動作します。 .txt ファイルのフォーマットは、 --fields-xxx--lines--xxx オプションに従います。
-u user_name, --user=user_name
サーバーに接続する際の MySQL ユーザー名。 デフォルトでは、UNIX のログイン名になります。
-O var=option, --set-variable var=option
変数の値をセット。 可能な変数は後で示しします。
-v, --verbose
冗長モード。 プログラムが何を行っているかより表示します。
-V, --version
バージョンを示して終了。
-w, --where='where-condition'
選択されたレコードのみをダンプ: クオートは必須です!
"--where=user='jimf'" "-wuserid>1" "-wuserid<1"
-O net_buffer_length=#, where # < 16M
When creating multi-row-insert statements (as with option --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.

mysqldump の普通の使用はデータベースのバックアップでしょう。 「22.2 データベースのバックアップ」節参照.

mysqldump --opt database > backup-file.sql

You can read this back into MySQL with:

mysql database < backup-file.sql

or

mysql -e "source /patch-to-backup/backup-file.sql" database

他の MySQL サーバーへデータベースをコピーする場合にも便利です:

mysqldump --opt database | mysql --host=remote-host -C database

It is possible to dump several databases with one command:

mysqldump --databases database1 [database2 database3...] > my_databases.sql

If all the databases are wanted, one can use:

mysqldump --all-databases > all_databases.sql

15.8 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, of single tables but it can only be run on the same machine where the database directories are.

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
Display a help screen and exit
-u, --user=#
User for database login
-p, --password=#
Password to use when connecting to server
-P, --port=#
Port to use when connecting to local server
-S, --socket=#
Socket to use when connecting to local server
--allowold
Don't abort if target already exists (rename it _old)
--keepold
Don't delete previous (now renamed) target when done
--noindices
Don't include full index files in copy to make the backup smaller and faster The indexes can later be reconstructed with myisamchk -rq..
--method=#
Method for copy (cp or scp).
-q, --quiet
Be silent except for errors
--debug
Enable debug
-n, --dryrun
Report actions without doing them
--regexp=#
Copy all databases with names matching regexp
--suffix=#
Suffix for names of copied databases
--checkpoint=#
Insert checkpoint entry into specified db.table
--flushlog
Flush logs once all tables are locked.
--tmpdir=#
Temporary directory (instead of /tmp).

You can use 'perldoc mysqlhotcopy' to get a more complete documentation for mysqlhotcopy.

mysqlhotcopy reads the group [mysqlhotcopy] from the option files.

15.9 テキストファイルからデータを取り込む ( mysqlimport )

mysqlimport は、LOAD DATA INFILE SQL 構文を、 コマンドラインインターフェースで提供します。 mysqlimport のオプションのほとんどが、 LOAD DATA INFILE への同じオプションに対応します。 「7.23 LOAD DATA INFILE構文」節参照.

mysqlimport の実行は以下のようにします:

shell> mysqlimport [options] database textfile1 [textfile2....]

mysqlimport は、コマンドラインの引数に与えられたファイル名の拡張子を取り、 拡張子を取った後の名前を、ファイルの内容を取り込むテーブルの名前とします。 例えば、`patient.txt', `patient.text', `patient' という ファイルは全て、patient とという名前のテーブルに取り込まれます。

mysqlimport は以下のオプションをサポートします:

-c, --columns=...
This option takes a comma-separated list of field names as an argument. The field list is used to create a proper LOAD DATA INFILE command, which is then passed to MySQL. 「7.23 LOAD DATA INFILE構文」節参照.
-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 の対応する文節と同じ意味になります。 「7.23 LOAD DATA INFILE構文」節参照.
-f, --force
エラーを無視します。例えば、テキストファイルを取り込むテーブルがない場合、 残りのファイルの処理に移ります。 --force がなければ、 テーブルがなければ mysqlimport は終了します。
--help
ヘルプを表示して終了。
-h host_name, --host=host_name
名前を指定された MySQL サーバーにデータを取り入れます。 デフォルトでは localhost.
-i, --ignore
--replace オプションの説明を見てください。
-l, --lock-tables
それぞれのテキストファイルを処理する前に、書き込まれる 全てのテーブルをロックします。 これは確実に、すべてのテーブルをサーバ上で同期させます。
-L, --local
クライアントからの入力ファイルを読みます。 デフォルトでは、localhost に接続した場合、テキストファイルは サーバー上にあると仮定されます。(localhost はデフォルト値)
-pyour_pass, --password[=your_pass]
サーバーに接続するときに使用するパスワード。 もし `=your_pass' のところにパスワードを書かなければ、 mysqlimport はパスワードのためのプロンプトをだします。
-P port_num, --port=port_num
ホストに接続するための TCP/IP ポート番号。 (これは localhost を除くホストへの接続に使用します。 localhost へは、UNIX ソケットを使用します。)
-r, --replace
--replace--ignore オプションは、 入力されているレコードのユニークキーの値が、 既に存在しているレコードのユニークキーの値と同じ場合、 その入力されているデータの取り扱いを決定します。 もし --replace が指定されているなら、 既にあるレコードは新しく読まれたレコードに置き換えられます。 もし --ignore が指定されているなら、 入力された物は無視されます。 どちらのオプションも指定していない場合、 キーの値が重なっているとエラーを発し、 テキストファイルの残りの部分は無視されます。
-s, --silent
静粛モード。エラーだけ出力します。
-S /path/to/socket, --socket=/path/to/socket
localhost への接続時に使用するソケットファイルを指定します。
-u user_name, --user=user_name
サーバーの接続に使用する MySQL ユーザー名の指定。 デフォルトは、Unix のログイン名。
-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 |
+------+---------------+

15.10 Converting an error code to the corresponding error message

perror can be used to print error message(s). perror can be invoked like this:

shell> perror [OPTIONS] [ERRORCODE [ERRORCODE...]]

For example:

shell> perror 64 79
Error code  64:  Machine is not on the network
Error code  79:  Can not access a needed shared library

perror can be used to display a description for a system error code, or an MyISAM/ISAM table handler error code. The error messages are mostly system dependent.

15.11 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. 「7.28 SHOW 構文」節参照.

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 wild-card (*, ?, % or _) then only what's matched by the wild card is shown. 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).

15.12 MySQL の圧縮された読み込み専用テーブルジェネレータ ( myisampackpack_isam )

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 はテーブル内の各項目を別々に圧縮するように働きます。展開のため の情報は、テーブルがオープンされた時にメモリに読まれます。これは、正確に1レコー ドだけを展開する必要があるような、個々のレコードへのアクセス時にとても良 い性能を与えます。MSDOS 上の Stacker 使用時のように、ディスクブロックは そんなに大きくありません。 通常、myisampack はデータファイルを 40~70% にパックします。

MySQL は圧縮されたテーブルでメモリマップ (mmap()) を使用します。 mmap() が働かない場合は、通常のファイルの読み書きを使用します。

現在 myisampack には2つの制限があります:

これらの制限の修正は TODO にありますが、優先度は低いです。

myisampack は以下のようにして起動します:

shell> myisampack [options] filename ...

それぞれのファイル名はインデックスファイル(`.MYI')の名前です。 もしデータディレクトリにカレントディレクトリを移動していないなら、 ファイルのパスを指定しなくてはなりません。`.MYI' 拡張子は 省略することが可能です。

myisampack は以下のオプションをサポートします:

-b, --backup
tbl_name.OLD としてバックアップを作成します.
-#, --debug=debug_options
デバック出力。debug_options'd:t:o,filename'.
-f, --force
一時ファイルが存在していようが、サイズが大きくなろうが、強制的にテーブルを パックします。 myisampack はテーブルを圧縮している間、 一時ファイルを `tbl_name.TMD' という名前で作成します。 もし myisampack を途中で kill した場合、 `.TMD' ファイルが消されて いない事があります。通常、myisampack`tbl_name.TMD' ファイルが 既に存在する場合はエラーで終了します。 --force を使用すると、 myisampack はそのような場合でもテーブルをパックします。
-?, --help
ヘルプメッセージを出力して終了。
-j big_tbl_name, --join=big_tbl_name
全てのテーブルをコマンドラインで指定した big_tbl_name 一つに まとめます。結合される全てのテーブル定義は同じでなければなりません (同じ項目名、同じ項目型、同じインデックス、等)
-p #, --packlength=#
Specify the record length storage size, in bytes. The value should be 1, 2, or 3. (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
Silent mode. Write output only when errors occur.
-t, --test
Don't actually pack table, just test packing it.
-T dir_name, --tmp_dir=dir_name
Use the named directory as the location in which to write the temporary table.
-v, --verbose
Verbose mode. Write information about progress and packing result.
-V, --version
Display version information and exit.
-w, --wait
Wait and retry if table is in use. If the mysqld server was invoked with the --skip-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 below illustrates a typical table compression session:

shell> ls -l station.*
-rw-rw-r--   1 monty    my         994128 Apr 17 19:00 station.ISD
-rw-rw-r--   1 monty    my          53248 Apr 17 19:00 station.ISM
-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.ISD
-rw-rw-r--   1 monty    my          55296 Apr 17 19:04 station.ISM
-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 below:

normal
The number of columns for which no extra packing is used.
empty-space
The number of columns containing values that are only spaces; these will occupy 1 bit.
empty-zero
The number of columns containing values that are only binary 0's; these will occupy 1 bit.
empty-fill
The number of integer columns that don't occupy the full byte range of their type; these are changed to a smaller type (for example, an INTEGER column may be changed to MEDIUMINT).
pre-space
The number of decimal columns that are stored with leading spaces. In this case, each value will contain a count for the number of leading spaces.
end-space
The number of columns that have a lot of trailing spaces. In this case, each value will contain a count for the number of trailing spaces.
table-lookup
The column had only a small number of different values, which were converted to an ENUM before Huffman compression.
zero
The number of columns for which all values are zero.
Original trees
The initial number of Huffman trees.
After join
The number of distinct Huffman trees left after joining trees to save some header space.

After a table has been compressed, myisamchk -dvv prints additional information about each field:

Type
The field type may contain the following descriptors:
constant
All rows have the same value.
no endspace
Don't store endspace.
no endspace, not_always
Don't store endspace and don't do end space compression for all values.
no endspace, no empty
Don't store endspace. Don't store empty values.
table-lookup
The column was converted to an ENUM.
zerofill(n)
The most significant n bytes in the value are always 0 and are not stored.
no zeros
Don't store zeros.
always zero
0 values are stored in 1 bit.
Huff tree
The Huffman tree associated with the field.
Bits
The number of bits used in the Huffman tree.

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.


Go to the first, previous, next, last section, table of contents.