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

用途说明

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

WelcometotheMySQLmonitor.Commandsendwith;or\g.

YourMySQLconnectionidis8toserverversion:3.23.58-log

Type'help;'or'\h'forhelp.Type'\c'toclearthebuffer.

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

Readingtableinformationforcompletionoftableandcolumnnames

Youcanturnoffthisfeaturetogetaquickerstartupwith-A

WelcometotheMySQLmonitor.Commandsendwith;or\g.

YourMySQLconnectionidis14687

Serverversion:5.1.48-community-logMySQLCommunityServer(GPL)

Copyright(c)2000,2010,Oracleand/oritsaffiliates.Allrightsreserved.

ThissoftwarecomeswithABSOLUTELYNOWARRANTY.Thisisfreesoftware,

andyouarewelcometomodifyandredistributeitundertheGPLv2license

Type'help;'or'\h'forhelp.Type'\c'toclearthecurrentinputstatement.

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

>selectcount(*)as"未评分数量",count(distinctquestion_seq)as"未评分题数"

>fromexam_user_answer

>wheredegreesisnull;

>EOF

+------------+------------+

|未评分数量|未评分题数|

+------------+------------+

|0|0|

+------------+------------+

[root@web exam_server]#

问题思考

相关资料

返回 我使用过的Linux命令系列总目录