mysql select 格式化输出

select * from test\G;html

MySQL的客户端命令行工具,有不少方便使用者的特性,某些方面甚至能够说比Oracle的sqlplus更加人性化。固然从总体来讲,仍是sqlplus更加方便些,这么说或许是我对sqlplus更加熟悉吧。这里记录下MySQL命令行几个比较经常使用的特性。

1.使用G按行垂直显示结果

若是一行很长,须要这行显示的话,看起结果来就很是的难受。在SQL语句或者命令后使用G而不是分号结尾,能够将每一行的值垂直输出。这个可能也是你们对于MySQL最熟悉的区别于其余数据库工具的一个特性了。

mysql> select * from db_archivelog\G
*************************** 1. row ***************************
id: 1
check_day: 2008-06-26
db_name: TBDB1
arc_size: 137
arc_num: 166
per_second: 1.6
avg_time: 8.7

2.使用pager设置显示方式

若是select出来的结果集超过几个屏幕,那么前面的结果一晃而过没法看到。使用pager能够设置调用os的more或者less等显示查询结果,和在os中使用more或者less查看大文件的效果同样。

使用more

mysql> pager more
PAGER set to ‘more’
mysql> P more
PAGER set to ‘more’

使用less

mysql> pager less
PAGER set to ‘less’
mysql> P less
PAGER set to ‘less’

还原成stdout

mysql> nopager
PAGER set to stdout

3.使用tee保存运行结果到文件

这个相似于sqlplus的spool功能,能够将命令行中的结果保存到外部文件中。若是指定已经存在的文件,则结果会附加到文件中。

mysql> tee output.txt
Logging to file ‘output.txt’

或者

mysql> T output.txt
Logging to file ‘output.txt’
mysql> notee
Outfile disabled.

或者

mysql> t
Outfile disabled

4.执行OS命令

mysql> system uname
Linux
mysql> ! uname
Linux

5.执行SQL文件

mysql> source test.sql
+—————-+
| current_date() |
+—————-+
| 2008-06-28 |
+—————-+
1 row in set (0.00 sec)

或者

mysql> . test.sql
+—————-+
| current_date() |
+—————-+
| 2008-06-28 |
+—————-+
1 row in set (0.00 sec)

其余还有一些功能,能够经过help或者?得到MySQL命令行支持的一些命令。
继续上面的的话题,介绍mysql命令行的一些小技巧
1.以html格式输出结果
使用mysql客户端的参数–html或者-T,则全部SQL的查询结果会自动生成为html的table代码

$ mysql -uroot –html Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 3286 Server version: 5.1.24-rc-log MySQL Community Server (GPL) Type ‘help;’ or ‘h’ for help. Type ‘c’ to clear the buffer. mysql> select * from test.test;
2 rows in set (0.00 sec)

2.以xml格式输出结果
跟上面差很少,使用–xml或者-X选项,能够将结果输出为xml格式

$ mysql -uroot –xml Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 3287 Server version: 5.1.24-rc-log MySQL Community Server (GPL) Type ‘help;’ or ‘h’ for help. Type ‘c’ to clear the buffer. mysql> select * from test.test;
2 rows in set (0.00 sec)

3.修改命令提示符
使用mysql的–prompt=选项,或者进入mysql命令行环境后使用prompt命令,均可以修改提示符

mysql> prompt u@d> PROMPT set to ‘u@d>’ root@(none)>use mysql Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed root@mysql>

其中u表示当前链接的用户,d表示当前链接的数据库,其余更多的可选项能够参考man mysql

这里再介绍下经过配置文件来设置MySQL命令行的这些参数。

经过/etc/my.cnf配置文件的[mysql]部分,能够设置MySQL命令行的一些运行参数。例如:

[mysql] prompt=\u@\d \r:\m:\s> pager=’less -S’ tee=’/tmp/mysql.log’

经过prompt设置显示用户名,当前数据库和当前时间,注意在配置文件里最好使用双斜杠:

root@poster 10:26:35>

经过pager设置使用less来显示查询结果,-S表示截断超过屏幕宽度的行,一行太长MySQL的显示格式就显得很乱,若是要看完整的行,建议使用G将行垂直输出。固然,你也能够添加更多less的参数来控制输出。

tee则将MySQL执行的全部输出保存到一个日志文件中,即便使用less -S截断了超长行,在日志中仍是会记录整个的结果,另外,前面经过prompt设置了当前时间显示,这样也便于在日志文件中查看每次操做的时间。因为tee的结果是附加到文件中的,日志文件须要按期清除。
相关文章
相关标签/搜索