zzxworld

MySQL 命令行操作指南

MySQL 命令行操作指南

mysql 命令是 MySQL 数据库提供的一个辅助工具。它不仅能直接连接数据库执行 SQL 语句,还能作为 shell,以交互方式来管理 MySQL 数据库。在不具备图形界面的环境,比如服务器上,可以把它作为 MySQL 数据库的客户端管理工具来使用。

基于它两种不同的使用方式,所以本文将分别来介绍一下它作为 shell 和命令时分别该如何使用。

mysql 作为 shell 使用

mysql 作为 shell,或者说是客户端使用时,需要先了解它的几个命令选项。

缩写 完整名称 说明
-h --host=服务器 指定 MySQL 服务器地址,默认为 127.0.0.1。
-u --user=用户名 指定连接 MySQL 服务器的用户名。
-p --password[=密码] 指定连接服务器的密码,如果不提供密码表示需要输入密码,命令执行后询问密码。
-P --port=# 指定连接端口,默认为 3306。

然后就可以执行如下的命令来连接 MySQL 服务器了:

mysql -uroot -p123456

执行上面的命令后,会以 root 用户名和 123456 这个简单的密码去连接本地的 MySQL 服务器。如果 MySQL 服务器安装配置无误,就能看到如下界面。

mysql shell

这是 mysql 命令提供的 shell 环境。随便在键盘上按几个字母,就会在下面 mysql> 后出现。这里即可以输入 shell 的内置命令,也可以输入 SQL 语句并执行。首先来看看它的内置命令,输入 help; 然后按回车,可以看到完整的命令列表:

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 the current input statement.
connect   (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set statement 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 not 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   (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets.
warnings  (\W) Show warnings after every statement.
nowarning (\w) Don not show warnings after every statement.
resetconnection(\x) Clean session context.

如果对某个命令不清楚,可以通过 help 命令来了解更详细的介绍。比如我想看看 use 命令该怎么用,就可以而输入 help use; 来查看:

mysql> help use;
Name: 'USE'
Description:
Syntax:
USE db_name

The USE statement tells MySQL to use the named database as the default
(current) database for subsequent statements. This statement requires
some privilege for the database or some object within it.

The named database remains the default until the end of the session or
another USE statement is issued:

USE db1;
SELECT COUNT(*) FROM mytable;   # selects from db1.mytable
USE db2;
SELECT COUNT(*) FROM mytable;   # selects from db2.mytable

The database name must be specified on a single line. Newlines in
database names are not supported.

这下就清楚了,只需要以 USE 数据库名; 的格式使用就行了。除了内置命令,更常见的用法是使用 SQL。操作数据表,查看数据都离不开 SQL。下面列举几个常见的案例。

比如要查看当前连接的 MySQL 服务上有那些可用的数据库:

SHOW DATABASES;

这样就可以得到有那些可用的数据库了。然后通过上面说的 use 命令来选择数据库:

USE wordpress;

接下来可以看看选择的数据库有哪些数据表:

SHOW TABLES;

浏览某个表的数据:

SELECT * FROM wp_posts;

根据需要,还可以使用 INSERTUPDATE, DELETE 来增加,编辑或是删除数据。这些纯粹的 SQL 操作就不多做介绍了。有一点需要注意,如果数据库中有中文内容,可能会显示成乱码,建议先执行一下下面的 SQL 语句:

SET NAMES utf8;

完成了需要的操作后,输入 exit; 或是 quit; 命令可以退出 shell 环境。如果习惯使用快捷键,可以按 Ctrl + d 组合键来退出。

我之前分享了一篇使用 shell 环境操作 MySQL 数据库账号和权限的文章,可以作为案例来参考使用:

mysql 作为命令使用

mysql 作为纯命令使用需要了解更多的命令选项,关于这方面的内容,可以参阅本文最后的命令选项参考。我专门整理成了一个表格。不过因为其中很多我也还没使用过,所以一时半会儿还无法翻译成便于理解的中文。有需要的朋友可以自己先行尝试,并欢迎在评论区分享你的体验结果。

了解 mysql 作为命令使用的更好方式是通过例子,所以这部分内容我就以几个自己常用的案例来说明。

案例一:直接执行 SQL 语句:

mysql -uroot -p123456 wordpress -e 'select * from wp_posts;'

这里在连接命令中直接指明了默认要选择的数据库 wordpress,并使用了 -e 选项来执行 SQL 语句。

案例二:导入 .sql 文件:

cat wordpress.sql | mysql -uroot -p123456 wordpress

上面的命名把 wordpress.sql 这个包含了 SQL 语句的文件通过 cat 命令传递给了 mysql 命令,mysql 命令通过执行这些 SQL 语句完成数据的导入。

mysql 命令选项参考

缩写 完整名称 说明
--abort-source-on-error Abort 'source filename' operations in case of errors
--auto-rehash Enable automatic rehashing. One doesn't need to use 'rehash' to get table and field completion, but startup and reconnecting may take a longer time. Disable with --disable-auto-rehash. (Defaults to on; use --skip-auto-rehash to disable.)
-A --no-auto-rehash No automatic rehashing. One has to use 'rehash' to get table and field completion. This gives a quicker start of mysql and disables rehashing on reconnect.
--auto-vertical-output Automatically switch to vertical output mode if the result is wider than the terminal width.
-B --batch Don't use history file. Disable interactive behavior. (Enables --silent.)
--binary-as-hex Print binary data as hex
--character-sets-dir=name Directory for character set files.
--column-type-info Display column type information.
-c --comments Preserve comments. Send comments to the server. The default is --skip-comments (discard comments), enable with --comments.
-C --compress 使用压缩协议。
-# --debug[=#] This is a non-debug version. Catch this and exit.
--debug-check Check memory and open file usage at exit.
-T --debug-info Print some debug info at exit.
-D --database=name 选择数据库。
--default-character-set=name 设置默认字符集。
--delimiter=name Delimiter to be used.
-e --execute=name 执行 mysql shell 内部命令或是 SQL 语句。
-E --vertical Print the output of a query (rows) vertically.
-f --force 忽略 SQL 错误并继续执行。
-G --named-commands Enable named commands. Named commands mean this program's internal commands; see mysql> help . When enabled, the named commands can be used from any line of the query, otherwise only from the first line, before an enter. Disable with --disable-named-commands. This option is disabled by default.
-i --ignore-spaces Ignore space after function names.
--init-command=name SQL Command to execute when connecting to MariaDB server. Will automatically be re-executed when reconnecting.
--local-infile Enable/disable LOAD DATA LOCAL INFILE.
-b --no-beep Turn off beep on error.
-h --host=服务器 指定 MySQL 服务器地址,默认为 127.0.0.1。
-H --html 以 HTML 格式输出内容。
-X --xml 以 XML 格式输出内容。
--line-numbers 给错误消息输出行号。
-L --skip-line-numbers 不给错误消息提供行号。
-n --unbuffered Flush buffer after each query.
--column-names 输出列表,这是命令的默认行为。
-N --skip-column-names 不输出列名。
--sigint-ignore 忽略 CTRL + C 类似的取消信号。
-o --one-database Ignore statements except those that occur while the default database is the one named at the command line.
--pager[=name] Pager to use to display results. If you don't supply an option, the default pager is taken from 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. Disable with --disable-pager. This option is disabled by default.
-p --password[=密码] 指定连接服务器的密码,如果不提供密码表示需要输入密码,命令执行后询问密码。
-P --port=# 指定连接端口,默认为 3306。
--progress-reports Get progress reports for long running commands (like ALTER TABLE) (Defaults to on; use --skip-progress-reports to disable.)
--prompt=name Set the command line prompt to this value.
--protocol=name The protocol to use for connection (tcp, socket, pipe).
-q --quick 不缓存结果,按行立即输出。
-r --raw Write fields without conversion. Used with --batch.
--reconnect 连接丢失是重连。
-s --silent Be more silent. Print results with a tab as separator, each row on new line.
-S --socket=name The socket file to use for connection.
--ssl Enable SSL for connection (automatically enabled with other flags).
--ssl-ca=name CA file in PEM format (check OpenSSL docs, implies --ssl).
--ssl-capath=name CA directory (check OpenSSL docs, implies --ssl).
--ssl-cert=name X509 cert in PEM format (implies --ssl).
--ssl-cipher=name SSL cipher to use (implies --ssl).
--ssl-key=name X509 key in PEM format (implies --ssl).
--ssl-crl=name Certificate revocation list (implies --ssl).
--ssl-crlpath=name Certificate revocation list path (implies --ssl).
--tls-version=name TLS protocol version for secure connection.
--ssl-verify-server-cert Verify server's "Common Name" in its cert against hostname used when connecting. This option is disabled by default.
-t --table Output in table format.
--tee=name Append everything into outfile. See interactive help (\h) also. Does not work in batch mode. Disable with --disable-tee. This option is disabled by default.
-u --user=用户名 指定连接 MySQL 服务器的用户名。
-U --safe-updates Only allow UPDATE and DELETE that uses keys.
-U --i-am-a-dummy Synonym for option --safe-updates, -U.
-w --wait 使用等待重连功能。
--connect-timeout=# Number of seconds before connection timeout.
--max-allowed-packet=# The maximum packet length to send to or receive from server.
--net-buffer-length=# The buffer size for TCP/IP and socket communication.
--select-limit=# Automatic limit for SELECT when using --safe-updates.
--max-join-size=# Automatic limit for rows in a join when using --safe-updates.
--secure-auth Refuse client connecting to server if it uses old (pre-4.1.1) protocol.
--server-arg=name Send embedded server this as a parameter.
--show-warnings 显示警告消息。
--plugin-dir=name Directory for client-side plugins.
--default-auth=name Default authentication client-side plugin to use.
--binary-mode Binary mode allows certain character sequences to be processed as data that would otherwise be treated with a special meaning by the parser. Specifically, this switch turns off parsing of all client commands except \C and DELIMITER in non-interactive mode (i.e., when binary mode is combined with either 1) piped input, 2) the --batch mysql option, or 3) the 'source' command). Also, in binary mode, occurrences of '\r\n' and ASCII '\0' are preserved within strings, whereas by default, '\r\n' is translated to '\n' and '\0' is disallowed in user input.
--connect-expired-password Notify the server that this client is prepared to handle expired password sandbox mode even if --batch was specified.
-v --verbose Write more. (-v -v -v gives the table output format).
-? --help 输出程序帮助信息。
-V --version 输出程序版本信息。