比CRUD多一点儿(一):MySQL经常使用命令

比CRUD多一点儿(一):MySQL经常使用命令

这是MySQL系列笔记的第一部分,本系列笔记但愿能按照笔者本身学习MySQL技术的经从来记录,避免纯粹按照内容一块一块总结,也就是不一样于通常按内容分配章节的书籍的结构,有一个平滑的阅读曲线。内容比较丰富的技术点会按照专题在多个学习笔记中逐渐深刻。文章列表点此html

首先,请若是还彻底为接触过MySQL的读者先阅读w3c的SQL教程,再来读本篇内容。mysql

这部分的标题叫比CRUD多一丁点儿,比起最基础的w3c的SQL教程以外,只多一点的扩展,知足应付从纯粹阅读入门资料到能够上手完成一个简单的工做的需求。sql

第一篇的主要内容会是最经常使用的一些mysql命令。由于虽然有不少图形化的工具,但在实际的工做中由于须要去线上服务查看数据,处理问题,字符界面的命令行工具是必不可少的。shell

客户端程序mysql:

链接交互式终端

mysql -h $host -P $port -u $user -p$passsword $database_name

例如用户root使用密码mydb@xxx用连接到地址为192.168.1.99,端口为3306的数mysql进程,并默认使用上名为testdb的数据库(即自动执行use testdb)。数据库

mysql -h 192.168.1.99 -P 3306 -u"root" -p"mydb@xx" testdb

各参数若是有@,&等bash的关键字,则须要用""引发来。segmentfault

非交互式的执行SQL

有时候须要在命令行执行某句SQL,则建议使用 -Bse 参数。-B参数的含义是执行多条语句(batch)这样能够执行多条,-e便是执行(execute),-s参数意思是静默执行(silent)可让输出格式精简一些。bash

mysql -h $host -P $port -u $user -p$passsword -Bse "command1;command2;....;commandn"

例如,常见的将执行结果导出到文件中方便留存和阅读。session

mysql -h 192.168.1.99 -P 3306 -u"root" -p"mydb@xx" -Bse "select id,name from testdb.Account;" > result.txt

导出程序mysqldump

mysqldump是作数据导出的命令行工具,也是mysql安装后默认会带的。做用是将mysql数据库中的数据导出出来。app

导出特定的表的内容

mysql -h $host -P $port -u $user -p$passsword $database_name $table1 $table2 ...

例如less

mysqldump -h 192.168.1.99 -P 3306 -u"root" -p"mydb@xx" mydb table1 table2 > result.sql

只导出表结构

使用--no-data参数只导出表结构,

mysqldump -h 192.168.1.99 -P 3306 -u"root" -p"mydb@xx" --no-data mydb  > result.sql

比较表结构mysqldiff

在开发实践中不免会遇到校验数据表结构不一样,或者根据开发环境和目标环境的表结构不一样来生成对应的表结构修改语句。mysql在5.7版本就提供了一个自带的mysqldiff工具。参数比较多,直接举例说明生成difftype=sql的ALTER语句的命令写法,以下:

mysqldiff --server1=root@host1 --server2=root@host2 \
          --show-reverse --difftype=sql \
          db1.table1:dbx.table3

# server1 on host1: ... connected.
# server2 on host2: ... connected.
# Comparing db1.table1 to dbx.table3                               [FAIL]
# Transformation statements:

# --destination=server1:
ALTER TABLE db1.table1
  ADD COLUMN notes char(30) AFTER a,
  CHANGE COLUMN misc misc char(55);

# --destination=server2:
# ALTER TABLE dbx.table3
#   DROP COLUMN notes,
#   CHANGE COLUMN misc misc char(30);

具体看mysql的官方文档:https://dev.mysql.com/doc/mys...

若是在mysql5.7版本如下就使用mysqldump命令参数输出简洁的表结构,随后diff文件而后自行编写ALTER语句吧。

mysqldump --skip-comments --skip-extended-insert -u root -p dbName1>file1.sql
mysqldump --skip-comments --skip-extended-insert -u root -p dbName2>file2.sql
diff file1.sql file2.sql

内建?, \s命令

心急火燎的进入mysql终端处理线上问题,这时候一个语法拼不对,还得切出去查手册?万一环境是内网不能上网就更是麻烦,其实mysql内建了帮助手册,能够直接在终端查询。

? 是交互式mysql终端内建的帮助命令。能够按照此帮助查阅文档等。其输出以下

mysql> ?

For information about MySQL products and services, visit:
   http://www.mysql.com/
For developer information, including the MySQL Reference Manual, visit:
   http://dev.mysql.com/
To buy MySQL Enterprise support, training, or other products, visit:
   https://shop.mysql.com/

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't 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't show warnings after every statement.
resetconnection(\x) Clean session context.

\s 可查看当前状态,版本,客户端ip,QPS等,\!能够在mysql终端中执行shell命令。在是不少处理问题的时候终端界面一进入mysql的交互式终端,就找不到ip、端口等在bash中的信息了又须要频繁切出,这两个命令都很是有用。\s输出以下:

mysql> \s
--------------
mysql  Ver 14.14 Distrib 5.7.12, for osx10.11 (x86_64) using  EditLine wrapper



Connection id:        2
Current database:    rizhiyi_system
Current user:        root@localhost
SSL:            Not in use
Current pager:        less
Using outfile:        ''
Using delimiter:    ;
Server version:        5.7.12 MySQL Community Server (GPL)
Protocol version:    10
Connection:        127.0.0.1 via TCP/IP
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    utf8
Conn.  characterset:    utf8
TCP port:        3306
Uptime:            21 sec

Threads: 1  Questions: 74  Slow queries: 0  Opens: 171  Flush tables: 1  Open tables: 164  Queries per second avg: 3.523
--------------

? contents 能够看内建的帮助手册

mysql> ? contents
You asked for help about help category: "Contents"
For more information, type 'help <item>', where <item> is one of the following
categories:
   Account Management
   Administration
   Compound Statements
   Data Definition
   Data Manipulation
   Data Types
   Functions
   Functions and Modifiers for Use with GROUP BY
   Geographic Features
   Help Metadata
   Language Structure
   Plugins
   Procedures
   Storage Engines
   Table Maintenance
   Transactions
   User-Defined Functions
   Utility

而后就能够继续查看子菜单帮助手册的内容,好比? Functions

mysql> ? Functions
You asked for help about help category: "Functions"
For more information, type 'help <item>', where <item> is one of the following
categories:
   Bit Functions
   Comparison operators
   Control flow functions
   Date and Time Functions
   Encryption Functions
   Information Functions
   Logical operators
   Miscellaneous Functions
   Numeric Functions
   String Functions

? insert 帮助命令还能够直接按关键字进行模糊查询,如:

mysql> ? insert
Name: 'INSERT'
Description:
Syntax:
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name
    [PARTITION (partition_name,...)]
    [(col_name,...)]
    {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
    [ ON DUPLICATE KEY UPDATE
      col_name=expr
        [, col_name=expr] ... ]

Or:

INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name
    [PARTITION (partition_name,...)]
    SET col_name={expr | DEFAULT}, ...
    [ ON DUPLICATE KEY UPDATE
      col_name=expr
        [, col_name=expr] ... ]

Or:

INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name
    [PARTITION (partition_name,...)]
    [(col_name,...)]
    SELECT ...
    [ ON DUPLICATE KEY UPDATE
      col_name=expr
        [, col_name=expr] ... ]

INSERT inserts new rows into an existing table. The INSERT ... VALUES
and INSERT ... SET forms of the statement insert rows based on
explicitly specified values. The INSERT ... SELECT form inserts rows
selected from another table or tables. INSERT ... SELECT is discussed
further in [HELP INSERT SELECT].

When inserting into a partitioned table, you can control which
partitions and subpartitions accept new rows. The PARTITION option
takes a comma-separated list of the names of one or more partitions or
subpartitions (or both) of the table. If any of the rows to be inserted
by a given INSERT statement do not match one of the partitions listed,
the INSERT statement fails with the error Found a row not matching the
given partition set. See
http://dev.mysql.com/doc/refman/5.7/en/partitioning-selection.html, for
more information and examples.

In MySQL 5.7, the DELAYED keyword is accepted but ignored by the
server. See [HELP INSERT DELAYED], for the reasons for this.

URL: http://dev.mysql.com/doc/refman/5.7/en/insert.html

本文中经常使用命令的更详细内容可看MySQL手册:
https://dev.mysql.com/doc/refman/5.7/en/programs-overview.html

相关文章
相关标签/搜索