Home Database Mysql Tutorial 十个节省时间的MySQL命令小结

十个节省时间的MySQL命令小结

Jun 07, 2016 pm 06:03 PM
mysql command

编者在工作中积累起来了一些MySQL命令行客户端技巧,这些技巧或多或少会帮助您节省大量的时间。

虽然有许多基于GUI的MySQL客户端存在,如著名的phpMyAdmin和SQLYog,但我一直喜欢原生的MySQL命令行客户端,的确,在未熟悉这些命令行接口(CLI)之前,我们需要花一些时间来熟悉它们,特别是你平时不是经常在具有强大的CLI环境的操作系统下工作时,但只要经过一些练习,你就可以通过CLI管理用户,浏览你的数据库和执行其它任务,其快感是其它人体会不到的。

在这篇文章中,我将会介绍我在工作中积累起来的一些MySQL命令行客户端技巧,不管你尝试其中一个还是所有技巧,我敢保证你一定会节省大量的时间。

顺便提一下,MySQL命令行客户端适应所有操作系统,当然包括Windows,但因为Windows原生CLI环境让人畏惧,因此推荐Windows用户下载并安装Console,它是Windows命令行的一个替代解决方案,提供了更强大的功能,如方便的文本选择,多标签窗口等。

1、登录过程自动化

正确配置的MySQL服务器需要你提供用户名和密码进行身份验证,通常情况下,我们可以直接在mysql命令后加上用户名,出于安全考虑,密码就不跟上了,回车执行时,命令提示符会提醒你输入密码。
代码如下:
%>mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or g. ...

通过这一个小小的改进,一年可以少输入几千次用户名,累计起来在登录时间上可以节省几个小时,创建一个.my.cnf文件,将其放在你的home目录下,如果是Windows,文件名则为my.ini,并且要放在MySQL安装目录下,在这个文件中,添加下面的代码,请使用你的登录信息替换占位符。
代码如下:
[client] host = your_mysql_server user = your_username password = your_password

一定要正确设置这个文件的权限,防止敏感数据被偷窥。

2、自动切换数据库

登录客户端后,你需要切换到目标数据库,通常我们会使用下面这个命令来切换数据库:
代码如下:
mysql>use wjgilmore_dev;

如果你想登录后自动切换到目标数据库,可以在上一步介绍的文件中添加下面的命令,注意位置也要放在[client]小节:
代码如下:
database = your_database_name

3、从脚本发送命令

设计一个新数据库时,我喜欢使用MySQL Workbench(MySQL工作台)设计模式和关系,它是一个特别强大的工具,你可以在图形界面下管理你的模式,然后同步到MySQL,或将SQL命令导出到一个文件,方便以后再导入到MySQL。

如果你喜欢手写代码,如创建大量的存储过程,或执行一个很长的连接,你可以将SQL保存为一个文件,然后将这个文件传递给客户端执行,如:
代码如下:
%>mysql

当然你需要指定连接字符串,或象前面一样通过配置文件来指定。

4、垂直显示结果

即使是很简单的表模式,也会包含几列字段,例如下面的表由11个字段组成,当我执行一个全结构查询时,输入结果如下:
代码如下:
mysql> select * from accounts where username = 'wjgilmore';
+----+-----------+------------------+------------------------------
----+----------+-----------+------------+-----------+--------------
--------------------+---------------------+---------------------+
| id | username | email | password | zip_code | latitude | longitude | confirmed | recovery | created_on | last_login |
+----+-----------+------------------+-------------------------------
---+----------+-----------+------------+-----------+-----------------
-----------------+---------------------+---------------------+
| 7 | wjgilmore | wj@wjgilmore.com | 2b877b4b825b48a9a0950dd5bd1f264d | 43201 | 39.984577 | -83.018692 | 1 | 8bnnwtqlt2289q2yp81tuge82fty501h | 2010-09-16 14:48:41 | 2010-10-27 15:49:44 |
+----+-----------+------------------+----------------------------------
+----------+-----------+------------+-----------+----------------------
------------+---------------------+---------------------+

显然我们不能接受,也无法阅读这种显示结果,使用G命令将上面丑陋的显示结果转换为垂直型。
代码如下:
mysql> select * from accounts where username = 'wjgilmore'G
*************************** 1. row ***************************
id: 7 username: wjgilmore email: wj@wjgilmore.com
password: 2b877b4b825b48a9a0950dd5bd1f264d zip_code: 43201
latitude: 39.984577 longitude: -83.018692
confirmed: 1 recovery: 8bnnwtqlt2289q2yp81tuge82fty501h
created_on: 2010-09-16 14:48:41 last_login: 2010-10-27 15:49:44

这样看起来就更舒服一点。

5、启用Tab键自动完成功能

重复输入表名和字段名无疑是很乏味的,给mysql客户端传递一个--auto-rehash参数,或是在my.ini文件中添加下面的命令来启用Tab键自动完成功能。
代码如下:
[mysql] auto-rehash

6、改变提示符

我不止一次想查看或修改被告知表不存在的模式,遇到这种情况我常常会很恐惧,大多数时候我登错数据库,导致错误地删除不该删除的表,通过修改MySQL客户端提示符,让它显示当前操作的数据库名字,从而避免误操作,为了让mysql客户端具备这种交互性,登录后执行下面的命令即可:
代码如下:
mysql>prompt [d]> [dev_wjgilmore_com]>

你可能希望永久保持这种效果,简单,只需要将下面的命令添加到你的配置文件中即可:
代码如下:
prompt = [d]>

当然不仅限于提示数据库名字,还可以显示当前日期和时间,主机名和用户名,请阅读MySQL手册了解更全面的信息。

7、使用安全更新预防灾难

前面我也提到,当表被意外删除时可能会引起恐惧,我相信不止我一个人有类似的经历,除了不小心执行了DROP TABLE外,更让人崩溃的是忽略WHERE子句的UPDATE命令,例如,假设你想使用下面的命令修改用户的用户名:
代码如下:
mysql>UPDATE users set User = 'wjgilmore' WHERE User = 'wjgilmore-temp';

但当你冲忙地想出去吃饭时,可能忘记敲入后面的WHERE子句
代码如下:
mysql>UPDATE users set User = 'wjgilmore';

一旦你按下回车,后果就很严重,users表中所有用户的用户名全部被修改为wjgilmore了,为了避免这种低级,但又会带来灾难性后果的错误,请在配置文件中添加下面的命令:
代码如下:
safe-updates

8、使用命令文档

许多用户都知道mysql客户端的内置文档,输入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. ...

如果你不知道DESCRIBE命令如何使用,只需要输入
代码如下:
mysql>help describe;
Name: 'DESCRIBE' Description: Syntax:
{DESCRIBE | DESC} tbl_name [col_name | wild] DESCRIBE provides information about the columns in a table.
It is a shortcut for SHOW COLUMNS FROM. These statements also display information for views. (See [HELP SHOW COLUMNS].) ...

9、使用Pager

有时你可能想查看表的某一行数据,但在屏幕上往往会显示满屏的数据,除了使用LIMIT子句外,开启客户端pager,设置你的系统分页实用程序:
代码如下:
mysql>pager more PAGER set to 'more'

如果要禁用pager,执行nopager命令即可。

10、将输出内容转储到文件

你可能偶尔需要将SQL执行结果输出到一个文本文件,可以使用SELECT INTO OUTFILE command命令达到目的,或直接在mysql客户端中启用tee命令,并制定输出文件实现同样的功能,如:
代码如下:
mysql>tee sales_report.txt

小结

不管你是挑选其中一部分还是尝试这10个技巧,它们都会为你节省大量的时间和精力,并会减轻你的痛苦,如果你知道其它MySQL命令行技巧,不妨在评论中一起分享一下吧!

原文出处:http://www.developer.com/db/10-command-line-timesavers-for-mysql-tasks.html

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Explain the role of InnoDB redo logs and undo logs. Explain the role of InnoDB redo logs and undo logs. Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

How does MySQL index cardinality affect query performance? How does MySQL index cardinality affect query performance? Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: From Small Businesses to Large Enterprises MySQL: From Small Businesses to Large Enterprises Apr 13, 2025 am 12:17 AM

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

See all articles