日期:2014-05-16  浏览次数:20737 次

我使用过的Linux命令之mysql - MySQL客户端命令行工具

我使用过的Linux命令之mysql - MySQL客户端命令行工具

本文链接:http://codingstandards.iteye.com/blog/975686 ? (转载请注明出处)

用途说明

mysql命令是用来连接MySQL服务器并执行用户命令行的工具,如果使用MySQL作为数据库,那这个命令就是经常需要用到的了。本文只简单讲述mysql命令行的使用,以及在shell脚本中的应用,不涉及mysql的安装和SQL语法介绍。

?

常用参数

格式:mysql

使用mysql连接数据库,只有在本机启动了mysql服务器,访问密码还没有设置的情况下才能连接成功。当然,还有一种情况就是在/etc/my.cnf的[mysql]节配置了user和password项的时候也可以做到。

?

格式:mysql -p

使用当前Linux登录用户连接mysql服务器,提示输入密码。

?

格式:mysql -pxxxxxx

使用当前Linux登录用户连接mysql服务器,密码为xxxxxx。

?

格式:mysql -uxxx -pxxxxxx

使用用户xxx,密码xxxxxx来连接mysql服务器。

?

格式:mysql -uxxx -pxxxxxx -hhostname

使用用户xxx,密码xxxxxx来连接运行在由hostname指定的主机上的mysql服务器。

?

参数: -s

安静模式,减少输出,比如表头(Silent mode. Produce less output.)。

?

参数:-r

输出的信息不进行转义,如果没有此参数,某些特殊字符将会被转义(Newline, tab, NUL, and backslash are written as \n, \t, \0, and \\.)

?

参数:-t

输出为表格形式(Display output in table format),在命令行方式默认输出为表格形式。但是作为脚本时如果要输出为表格形式那么就必须加上此参数。

?

参数:-H

输出为HTML形式(Produce HTML output.)。

?

使用示例

示例一

[root@node34 root]# mysql
Welcome to the MySQL monitor.? Commands end with ; or \g.
Your MySQL connection id is 8 to server version: 3.23.58-log

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> quit
Bye
[root@node34 root]#

?

示例二 访问MySQL数据库的脚本

有时候觉得访问mysql时总是要输入用户和密码、主机之类的很烦,索性就写一个简单的shell脚本来访问它。

?

文件:db.sh

#!/bin/sh

mysql -pxxxxxx -uroot -h192.168.6.xx exam "$@"

?

[root@web exam_server]# ./db.sh
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.? Commands end with ; or \g.
Your MySQL connection id is 14687
Server version: 5.1.48-community-log MySQL Community Server (GPL)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> quit
Bye
[root@web exam_server]#

下面的命令将mysql的查询结果输出为HTML文本,这个可以用在shell脚本中。

[root@web exam_server]# ./db.sh -H <<EOF

show tables;

EOF

<TABLE BORDER=1><TR><TH>Tables_in_exam</TH></TR><TR><TD>exam_paper_info</TD></TR><TR><TD>exam_paper_question</TD></TR><TR><TD>exam_question_info</TD></TR><TR><TD>exam_user_answer</TD></TR><TR><TD>exam_user_info</TD></TR><TR><TD>exam_user_paper</TD></TR></TABLE>

下面的命令将mysql的查询结果输出为表格形式,这个可以用在shell脚本中。注:在shell脚本中要输出表格形式,必须加上-t参数。

[root@web exam_server]# ./db.sh -t <<EOF
> select count(*) as "未评分数量", count(distinct question_seq) as "未评分题数"
> from exam_user_answer
> where degrees is null;
> EOF

+------------+------------+
| 未评分数量 | 未评分题数 |
+------------+------------+
|????????? 0 |????????? 0 |
+------------+------------+
[