广义查询:

DML:

  DELETE 删除数据

  INSERT INTO 插入数据

  UPDATE 更新数据

INSERT INTO tb_name (col1,col2,...) VALUES (val1,val2,...)[,(val1,val2,...),...] 可以实现批量插入,字符串要用''单引号引起来;

  字符型: 单引号

  数值型: 不需要引号

  日期时间型: 不需要引号

  空值: NULL,

REPLACE INTO 替换原来数据,和INSERT INTO用法相同;

DELETE:

  DELETE FROM tb_name WHERE condition;(如果不小心删除某张表,只能通过备份,这个操作非常危险的,MySQL有个内置法则可以实现如果使用DELETE语句或者UPDATE语句时候没有使用WHERE条件子句它不让你执行,以免产生误操作)

TRUNCATE tb_name: 清空表的数据,并且重置AUTOINCREMENT(自动增长)计数器;

UPDATE tb_name SET col1=...,col2=... WHERE (更新某个字段数据)

 

MySQLAdministrator(MySQL 管理)

MySQL基础架构

面对用户的是连接管理器,而后接收用户连接并建立连接之后下一层是查询缓存和分析器,如果缓存中有结果,那就从高速缓存中直接返回用户的查询结果,如果是UPDATE、DELETE语句就不涉及到查询结果,因为他们是更新操作,所以查询缓存只跟读操作有关系,跟写操作没有关系,而且只跟读操作当中的查询操作有关系,如果缓存没有命中,于是交由分析器做分析,分析的结果如果发现缓存中仍然有结果可以交由缓存直接从缓存返回结果,否则交给优化器完成优化,而后再交由存储引擎,我们的执行引擎,由执行引擎最后交给存储引擎完成语句执行,连接管理器主要作用接收客户端请求,监听在某个套接字上接收客户端请求,接收下来之后给它创建一个线程用于响应,于是线程还有线程管理器专门来负责相关功能,为了加速线程的创建,我们的用户如果非常多,而且非常频繁的话,我们的线程频繁的创建并销毁是相当消耗资源的,于是就有了线程重用的概念,一个用户连接进来之后退出了线程没有被销毁,而是直接放到空闲线程池当中,而后新的用户请求到来之后直接给它拿一个空闲线程响应,类似于prefork模型,当给用户创建线程来进行响应之后,要验证用户是否能够允许连入mysql服务器,如果我们当前主机只有1颗CPU,或者只有有限的CPU核心数,我们这里又连接进来了N个用户,每个用户都有一个线程,每一个用户自己所有的操作都在它自身线程地址空间内完成,而我们的CPU是有限的,也就意味着每一个用户所发起的操作只能轮流在CPU执行,而如果说某个查询速度非常慢,执行速度又非常慢,结果导致一个用户的查询虽然很简单,但是执行起来仍然会很慢,因为此前仍在执行没结束,所以像这些所谓的每一个查询操作,每一个用户的线程最终都要轮流在CPU上执行,而这个轮流执行过程很有可能受到其它线程的影响,而且这种彼此间的影响还是非常大的,MySQL在实现远程连接的时候我们的查询操作数据一定是通过网络发送的,我们把请求的语句发送到服务器端,服务器的执行结果在返回给客户端,这个过程是加密的还是明文的,MySQL协议是明文的,如果说我们的数据涉及到非常大的机密性该怎么办,也就意味着我们的会话管理器还要负责实现建立加密会话,当我们发起查询操作以后MySQL服务器会负责解析每一个查询,并且在MySQL的进程内部创建一个解析树,它会去解析每一个请求,并为这个请求创建出来一个叫解析树,到底该怎么去执行,然后在这个解析树的进行各种优化并计算出最优执行路径,所以这就是解析器和优化器的作用,优化器的优化是自我判定的,它跟我们实际场景可能会有出入,因为优化器是在程序的基础上做的智能判定,但是程序本身它未必是能够像人一样随时考虑到各种各样的变化情况,所以虽然叫做优化器,但它优化的结果未必一定是最佳结果,如果作为用户来讲我们自己知道哪一种方式更优,我们可以给优化提示,在执行语句的时候,给它来一个简单的提示告诉它要使用那个索引可能会更好,这样就避免优化器自动再去挑选索引再去计算执行路径的开销等情况了,所以这一切都是优化器和解析器共同完成的,更重要的是MySQL由于是插件式存储引擎使得优化器在实现度量的时候,在实现开销衡量的时候它是不会去考虑存储引擎的不同的,也就意味着它其实并不能意识到MyISAM和InnoDB有什么不同,这也十个缺陷,这也是我们有时候需要给优化器提示的原因,每一个查询执行结束之后,如果它的结果是决定性的,MySQL还会将它的查询结果给它缓存下来,这就是缓存器,主要为了结果重用,当同样的查询语句再次执行的时候可以直接从缓存结果中返回,但是要考虑几点,第一缓存是不是有限的,如果查询语句查询一个百万行表中的所有内容,就不能缓存下来,所以不是所有结果都可以缓存,一定是小于某个上限的,同样如果查询语句查询的结果非常非常小,只有10个字节,为了有效管理缓存我们缓存当中的内容可能被分为多个区域,假如分为三个区域,每一个区域内部有一个称为叫做缓存槽的东西,我们以后每一个查询结果要占据这个槽,为了方便管理这些槽最小下线,比如每一个槽位最小为512字节,但是如果我们查询的结果为4个字节缓存都要占用一个槽,那512字节里面除了这4个字节之外剩下的全部都是浪费的,这是非常麻烦的,如果我们不浪费我们自己按照需要去缩减这个缓存空间的话也会使得缓存中产生大量的碎片的,因为缓存中会不停的生效失效,所以时间久了会产生大量碎片,有着大量碎片的缓存它的执行效率也不会好,所以缓存管理是非常非常复杂的,于是为了尽可能提高缓存的工作效率发挥它的性能,必须要对缓存做出一定的优化,而且做出限定,不是所有的结果都可以缓存,还有有些结果更不能缓存,比如看当前时间,每次执行结果都不一样,这种叫做非确定性结果,像这种查询结果我们一般也不记录缓存的,所以缓存并不是所有情况下都缓存,而只是缓存有些特定的结果,更重要的是就算两个语句一模一样它也未必能使用缓存,一个用户连接进来发起一个查询语句,另外一个用户连接进来发起一个一模一样的查询语句,但是另外一个用户压根就么有权限,要是直接从缓存中直接返回就麻烦了,所以实施在缓存中的策略比我们想象的要复杂的多,而且有了缓存以后带来的结果未必都是优势,如果没有缓存每一次查询直接交给解析树解析就可以了,如果有了缓存每一次查询之前都得先看看缓存中是否命中,如果缓存中没有再去找解析树,这会导致我们的语句很大一部分白白要去找一次缓存,这事实上是额外开销,所以我们必须要计算出来最佳的平衡点,使得它的开销一定小于它所带来的益处的才有意义,以及缓存本身所扮演的角色所起到的作用等等,如果两个用户同时连进来发起一个请求,第一个用户视图去写表A,第二个用户试图去从表A查询的怎么办,一个读操作一个查操作同时发起,他们同时请求的是同一张表,这该怎么办,我们是一前一后还是可以让二者同时并行执行,无论是任何样的场景不仅仅包括数据库,任何时候只要有两个用户试图同时读写同一个文件的时候都会带来所谓的并发控制的问题,就以此前的mbox邮箱为例,这里面是一个文件存储多封邮件,然后是一封邮件接一封邮件,如果有两个MDA进程同时往邮箱里面投递两封不同邮件会发生什么情况,我们mbox文件只有一个,两封信交替往里面投递会发生什么结果,第一封信写一行,第二封信写一行,第三封信写一行,第四封写一行,最后发现是两封信合并成一封,杂乱无章,所以这就意味着有同时的读写操作,或者同时的写操作,这时候怎么办,我们必须要有所谓的并发控制机制使得一个用户的操作或者一个进程操作不会影响到另外一个进程操作,我们并发的目的是为了提高性能,但是在同一个数据上要产生并发访问量我们又不得不使用额外的非常复杂的机制来解决并发控制的问题,事实上并发控制非常复杂,对任何系统都是这样子,对于简单的模型来讲,比如在一个操作系统上的文件系统里面两个用户如果同时编辑一个文件怎么实现并发控制,无非就是加锁,其它用户发现有这个锁不让它执行就可以了,但是MySQL这样的C/S架构的服务器一个用户怎么知道另一个用户正在操作数据,它不知道,由此我们服务器必须要完成并发控制,但是像MySQL这样的服务器有可能连接进来的量是非常大的,50个用户或100个用户同时来访问同一个文件,那这个时候我们要解决的并发问题可能就比我们想象的复杂的多的多,如果我们串型,一个完成另外一个继续,那这就麻烦了,比如第一个用户发起写操作,它执行了10分钟才把数据插入进去,而第二个用户就是从这个表中查一行数据,结果它要等待人家10分钟完成,它会发现数据库这么慢,查询一个简单的数据就要等10分钟以上,这很麻烦,现在像很多的数据库服务器都引入了多版本并发控制的概念,每一个用户在操作数据的时候操作的都不是原数据,而是一个副本或一个快照,最后再完成快照合并,当然为了避免彼此之间冲突,一个用户查询了别人正在修改的行的话,就算使用快照,它也涉及到非常复杂的控制机制,多版本并发控制它所实现的操作就是每一个用户实现操作的时候不是直接在原数据上操作,而是给你个时间版本,比如说在某一时候某个用户发起了写操作,它于是在当前这个时刻给你创建一个数据的快照,你操作的是一个快照,而且这个快照有一个时间值,明确告诉你这个快照什么时间创建的,第二个用户查询仍然给它一个快照而且给它一个时间点,所以是个时间快照,最后操作的结果会把这些快照再合并到原数据上去,合并的时候还要依赖这些时间点来判定谁在先谁在后,不然的话一个用户删除一行,另外一个用户正好修改了这行,这个行到底是保留还是不保留,我们必须要以谁在后面发起的操作为准,这就是所谓的多办法并发控制,这是服务器所必须具备的能力,要想实现并发控制,一个基础的工具就是锁,最简单的并发控制就是实时锁,锁有很多种类型,比如同一个文件,一个用户读另一个用户可以读,但读不允许别人写,写的只能读一半,于是像这种锁叫共享锁,而写的时候是独占锁,写的时候不允许其它人写也不允许其它人读,大多数情况下MySQL会自动实施枷锁,比如UPDATE一个数据,这时候导致其它用户的读请求或者写请求会按照MySQL内在逻辑来进行控制,作为用户来讲我们也可以明确的手动施加锁;

连接管理器:

  接受请求

  创建线程

  认证用户

  建立安全连接

并发控制:

  mbox: MDA

  C/S: 100

    10分组:

    多版本并发控制:MVCC

锁:

  读锁: 共享锁

  写锁: 独占锁

    LOCK TABLES tb_name {READ|WRITE} 加锁

    UNLOCK TABLES 解除所有表的锁

锁粒度: 从大到小,MySQL服务器仅支持表级锁,行锁需要由存储引擎完成;

  表锁: 锁定一张表;

  页锁: 锁定数据块,可能锁定多个行;

  行锁: 锁定某些行

事务:

  RDBMS: ACID(原子性,一致性,隔离性,持久性)

    原子性: 一个操作要么同时完成,要么同时不完成;

    一致性: 事务在完成之前和完成之后结果一定是一致的;

    隔离性: 如果两个事务同时执行,那么第一个事务的操作在完成之前不能被第二个事务所察觉到;

    持久性: 一旦一个事务提交了完成了,那么就算我们的服务器down机了,下次启动起来必须要保证这个数据仍然是在服务器上是可看到的,在事务完成以后要立即同步到外部存储上去;

  MyISAM: 不支持事务

  InnoDB: 支持事务

事务日志

重做日志: redo log 我们每一个操作在真正写到数据库上之前它先写到日志里面去了,下次我们这个操作就算崩溃了它还可以根据我们的重做日志记录再走一遍,也就意味我们这一系列操作可以无限制根据这个日志重复执行N遍;

撤销日志: undo log 我们每一次操作在操作之前要把它原有的状态给它保留下来万一将来我们需要还原回原来状态的时候可以给它撤销此前所做的任何一次操作;

日志组

隔离型

  隔离级别:MySQL默认是REPATABLE READ级别,隔离级别越高,并发能力越低;

    READ UNCOMITED: 读未提交

    READ COMITED: 读提交 别人只有提交以后才能看到

    REPATABLE READ: 可重读 开始看到什么样到事务提交看到是什么样

    SERTABLIZABLE: 可串行


服务器变量:

动态:

  全局变量

    修改后不影响当前会话,只对新简历的会话有效;

  会话变量

    仅对当前会话有效,而且是立即生效;

  永久有效: 修改配置文件

修改: SET {SESSION|GLOBAL} VAR_NAME='';

[root@localhost ~]# mysql(连接mysql数据库)
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 27
Server version: 5.5.28-log Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql> HELP INSERT(查看插入数据帮助)
Name: 'INSERT'
Description:
Syntax:
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name [(col_name,...)]
    {VALUES | VALUE} ({expr | DEFAULT},...),(...),...(expr表达式,)
    [ ON DUPLICATE KEY UPDATE
      col_name=expr
        [, col_name=expr] ... ]

Or:

INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE](只能插入一行)
    [INTO] tbl_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 [(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].

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

[root@localhost ~]# mysql(连接mysql数据库)
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 28
Server version: 5.5.28-log Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql> USE jiaowu;(修改默认数据库为jiaowu)
Database changed

mysql> SHOW TABLES;(显示当前数据库有那些表)
+------------------+
| Tables_in_jiaowu |
+------------------+
| courses          |
| scores           |
| sct              |
| students         |
| tutors           |
+------------------+
5 rows in set (0.00 sec)

mysql> DESC tutors;(显示tutors表结构)
+--------+----------------------+------+-----+---------+----------------+
| Field  | Type                 | Null | Key | Default | Extra          |
+--------+----------------------+------+-----+---------+----------------+
| TID    | smallint(5) unsigned | NO   | PRI | NULL    | auto_increment |
| Tname  | varchar(50)          | NO   |     | NULL    |                |
| Gender | enum('F','M')        | YES  |     | M       |                |
| Age    | tinyint(3) unsigned  | YES  |     | NULL    |                |
+--------+----------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> INSERT INTO tutors SET Tname='Tom',Gender='F',Age=30; (像tutors表的Tname字段、Gender字段、Age字段插入数据) 
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM tutors;(查询tutors表的所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
+-----+--------------+--------+------+
10 rows in set (0.00 sec)

mysql> SELECT * FROM tutors ORDER BY TID DESC LIMIT 1;(显示tutors表的所有字段条件降序排序显示第一个)
+-----+-------+--------+------+
| TID | Tname | Gender | Age  |
+-----+-------+--------+------+
|  10 | Tom   | F      |   30 |
+-----+-------+--------+------+
1 row in set (0.00 sec)

提示:如果中间删除某个用户,比如把4号TID删除,我们在插入的新用户它的TID为4还是为11号,应该为11号,注意,就算把这个表完全清空下次插入的数据它也是从第11号开始的,因
为它此前所做的计数仍然保留在一个内置函数当中;

mysql> SELECT LAST_INSERT_ID();(查看LAST_INSERT_ID函数值)
+------------------+
| LAST_INSERT_ID() |
+------------------+
|               10 |
+------------------+
1 row in set (0.00 sec)

mysql> DESC students;(查看students表结构)
+------------+----------------------+------+-----+---------------------+----------------+
| Field      | Type                 | Null | Key | Default             | Extra          |
+------------+----------------------+------+-----+---------------------+----------------+
| SID        | smallint(5) unsigned | NO   | PRI | NULL                | auto_increment |
| Name       | varchar(50)          | NO   |     | NULL                |                |
| Age        | tinyint(3) unsigned  | YES  |     | NULL                |                |
| Gender     | enum('F','M')        | YES  |     | M                   |                |
| CID1       | smallint(5) unsigned | YES  |     | NULL                |                |
| CID2       | smallint(5) unsigned | YES  |     | NULL                |                |
| TID        | smallint(6)          | YES  |     | NULL                |                |
| CreateTime | datetime             | YES  |     | 2012-04-06 10:00:00 |                |
+------------+----------------------+------+-----+---------------------+----------------+
8 rows in set (0.00 sec)

mysql> DESC tutors;(查看tutors表结构)
+--------+----------------------+------+-----+---------+----------------+
| Field  | Type                 | Null | Key | Default | Extra          |
+--------+----------------------+------+-----+---------+----------------+
| TID    | smallint(5) unsigned | NO   | PRI | NULL    | auto_increment |
| Tname  | varchar(50)          | NO   |     | NULL    |                |
| Gender | enum('F','M')        | YES  |     | M       |                |
| Age    | tinyint(3) unsigned  | YES  |     | NULL    |                |
+--------+----------------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)

mysql> SELECT Name,Gender,Age FROM students WHERE Age>20;(查询students表Name、Gender、Age字段条件Age大于20的数据)
+-------------+--------+------+
| Name        | Gender | Age  |
+-------------+--------+------+
| DingDian    | M      |   25 |
| HuFei       | M      |   31 |
| Xuzhu       | M      |   26 |
| LingHuchong | M      |   22 |
| stu1        | F      |   23 |
+-------------+--------+------+
5 rows in set (0.00 sec)

mysql> INSERT INTO tutors (Tname,Gender,Age) SELECT Name,Gender,Age FROM students WHERE Age>20;(将查询students表Name、Gender、Age字段条件Age
大于20的数据插入到Tutors表的Tname、Gender、Age字段)
Query OK, 5 rows affected (0.01 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM tutors;(查询tutors表的所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   31 |
|  13 | Xuzhu        | M      |   26 |
|  14 | LingHuchong  | M      |   22 |
|  15 | stu1         | F      |   23 |
+-----+--------------+--------+------+
15 rows in set (0.00 sec)

mysql> HELP REPLACE(查看替换命令帮助)
Name: 'REPLACE'
Description:
Syntax:
REPLACE [LOW_PRIORITY | DELAYED]
    [INTO] tbl_name [(col_name,...)]
    {VALUES | VALUE} ({expr | DEFAULT},...),(...),...

Or:

REPLACE [LOW_PRIORITY | DELAYED]
    [INTO] tbl_name
    SET col_name={expr | DEFAULT}, ...

Or:

REPLACE [LOW_PRIORITY | DELAYED]
    [INTO] tbl_name [(col_name,...)]
    SELECT ...

REPLACE works exactly like INSERT, except that if an old row in the
table has the same value as a new row for a PRIMARY KEY or a UNIQUE
index, the old row is deleted before the new row is inserted. See [HELP
INSERT].

REPLACE is a MySQL extension to the SQL standard. It either inserts, or
deletes and inserts. For another MySQL extension to standard SQL---that
either inserts or updates---see
http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html.

Note that unless the table has a PRIMARY KEY or UNIQUE index, using a
REPLACE statement makes no sense. It becomes equivalent to INSERT,
because there is no index to be used to determine whether a new row
duplicates another.

Values for all columns are taken from the values specified in the
REPLACE statement. Any missing columns are set to their default values,
just as happens for INSERT. You cannot refer to values from the current
row and use them in the new row. If you use an assignment such as SET
col_name = col_name + 1, the reference to the column name on the right
hand side is treated as DEFAULT(col_name), so the assignment is
equivalent to SET col_name = DEFAULT(col_name) + 1.

To use REPLACE, you must have both the INSERT and DELETE privileges for
the table.

URL: http://dev.mysql.com/doc/refman/5.5/en/replace.html

mysql> HELP DELETE(查看删除命令帮助)
Name: 'DELETE'
Description:
Syntax:
Single-table syntax:(单表)

DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name(tb1_name表名)
    [WHERE where_condition](条件)
    [ORDER BY ...](排序)
    [LIMIT row_count](限定行数)

Multiple-table syntax:(多表)

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    tbl_name[.*] [, tbl_name[.*]] ...
    FROM table_references
    [WHERE where_condition]

Or:

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    FROM tbl_name[.*] [, tbl_name[.*]] ...
    USING table_references
    [WHERE where_condition]

For the single-table syntax, the DELETE statement deletes rows from
tbl_name and returns a count of the number of deleted rows. This count
can be obtained by calling the ROW_COUNT() function (see
http://dev.mysql.com/doc/refman/5.5/en/information-functions.html). The
WHERE clause, if given, specifies the conditions that identify which
rows to delete. With no WHERE clause, all rows are deleted. If the
ORDER BY clause is specified, the rows are deleted in the order that is
specified. The LIMIT clause places a limit on the number of rows that
can be deleted.

For the multiple-table syntax, DELETE deletes from each tbl_name the
rows that satisfy the conditions. In this case, ORDER BY and LIMIT
cannot be used.

where_condition is an expression that evaluates to true for each row to
be deleted. It is specified as described in
http://dev.mysql.com/doc/refman/5.5/en/select.html.

Currently, you cannot delete from a table and select from the same
table in a subquery.

You need the DELETE privilege on a table to delete rows from it. You
need only the SELECT privilege for any columns that are only read, such
as those named in the WHERE clause.

As stated, a DELETE statement with no WHERE clause deletes all rows. A
faster way to do this, when you do not need to know the number of
deleted rows, is to use TRUNCATE TABLE. However, within a transaction
or if you have a lock on the table, TRUNCATE TABLE cannot be used
whereas DELETE can. See [HELP TRUNCATE TABLE], and [HELP LOCK].

URL: http://dev.mysql.com/doc/refman/5.5/en/delete.html

提示:当我们使用DELETE删除某张表中所有内容的时候,就算我们需要删除所有内容,一旦删除以后我们插入的新的行它的ID行的计数仍然从上一次插入的最后一个开始计数,如果期
望从新开始计数;

mysql> HELP TRUNCATE(查看)
Name: 'TRUNCATE'
Description:
Syntax:
TRUNCATE(X,D)

Returns the number X, truncated to D decimal places. If D is 0, the
result has no decimal point or fractional part. D can be negative to
cause D digits left of the decimal point of the value X to become zero.

URL: http://dev.mysql.com/doc/refman/5.5/en/mathematical-functions.html

Examples:
mysql> SELECT TRUNCATE(1.223,1);(截取字符串只保留几位)
        -> 1.2
mysql> SELECT TRUNCATE(1.999,1);
        -> 1.9
mysql> SELECT TRUNCATE(1.999,0);
        -> 1
mysql> SELECT TRUNCATE(-1.999,1);
        -> -1.9
mysql> SELECT TRUNCATE(122,-2);
       -> 100
mysql> SELECT TRUNCATE(10.28*100,0);
       -> 1028

mysql> DELETE FROM students;(删除students表中数据)
Query OK, 11 rows affected (0.00 sec)

mysql> SELECT * FROM students;(查询students表所有字段数据)
Empty set (0.00 sec)

mysql> DESC students;(查看students表结构)
+------------+----------------------+------+-----+---------------------+----------------+
| Field      | Type                 | Null | Key | Default             | Extra          |
+------------+----------------------+------+-----+---------------------+----------------+
| SID        | smallint(5) unsigned | NO   | PRI | NULL                | auto_increment |
| Name       | varchar(50)          | NO   |     | NULL                |                |
| Age        | tinyint(3) unsigned  | YES  |     | NULL                |                |
| Gender     | enum('F','M')        | YES  |     | M                   |                |
| CID1       | smallint(5) unsigned | YES  |     | NULL                |                |
| CID2       | smallint(5) unsigned | YES  |     | NULL                |                |
| TID        | smallint(6)          | YES  |     | NULL                |                |
| CreateTime | datetime             | YES  |     | 2012-04-06 10:00:00 |                |
+------------+----------------------+------+-----+---------------------+----------------+
8 rows in set (0.00 sec)

mysql> INSERT INTO students (Name,Age,Gender) VALUES ('tom',30,'F');(像students表的Name、Age、Gender字段插入数据)
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM students;(查看students表所有字段数据)
+------+------+------+--------+------+------+------+---------------------+
| SID  | Name | Age  | Gender | CID1 | CID2 | TID  | CreateTime          |
+------+------+------+--------+------+------+------+---------------------+
| 3908 | tom  |   30 | F      | NULL | NULL | NULL | 2012-04-06 10:00:00 |
+------+------+------+--------+------+------+------+---------------------+
1 row in set (0.00 sec)

提示:SID很大,不是从1开始的;

mysql> INSERT INTO students (Name,Age,Gender) VALUES ('jerry',30,'F');(向students表的Name、Age、Gender字段插入数据)
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM students;(查看students表所有字段数据)
+------+-------+------+--------+------+------+------+---------------------+
| SID  | Name  | Age  | Gender | CID1 | CID2 | TID  | CreateTime          |
+------+-------+------+--------+------+------+------+---------------------+
| 3908 | tom   |   30 | F      | NULL | NULL | NULL | 2012-04-06 10:00:00 |
| 3909 | jerry |   30 | F      | NULL | NULL | NULL | 2012-04-06 10:00:00 |
+------+-------+------+--------+------+------+------+---------------------+
2 rows in set (0.00 sec)

mysql> TRUNCATE students;(清空students表数据并且情况AUTOINCREMENT数值)
Query OK, 0 rows affected (0.05 sec)

mysql> INSERT INTO students (Name,Age,Gender) VALUES ('tom',30,'F');(向students表的Name、Age、Gender字段插入数据)
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM students;(查询students表的所有字段数据)
+-----+------+------+--------+------+------+------+---------------------+
| SID | Name | Age  | Gender | CID1 | CID2 | TID  | CreateTime          |
+-----+------+------+--------+------+------+------+---------------------+
|   1 | tom  |   30 | F      | NULL | NULL | NULL | 2012-04-06 10:00:00 |
+-----+------+------+--------+------+------+------+---------------------+
1 row in set (0.00 sec)

提示:SID从1开始计数,这就是TRUNCATE和DELETE清空表数据的区别;

mysql> HELP UPDATE(查看更新命令语法帮助)
Name: 'UPDATE'
Description:
Syntax:
Single-table syntax:(单表)

UPDATE [LOW_PRIORITY] [IGNORE] table_reference(table_reference表名)
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...(SET设定某个字段更新为对应某个值)
    [WHERE where_condition](WHERE设定条件)
    [ORDER BY ...](排序)
    [LIMIT row_count](限定行数)

Multiple-table syntax:(多表)

UPDATE [LOW_PRIORITY] [IGNORE] table_references
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
    [WHERE where_condition]

For the single-table syntax, the UPDATE statement updates columns of
existing rows in the named table with new values. The SET clause
indicates which columns to modify and the values they should be given.
Each value can be given as an expression, or the keyword DEFAULT to set
a column explicitly to its default value. The WHERE clause, if given,
specifies the conditions that identify which rows to update. With no
WHERE clause, all rows are updated. If the ORDER BY clause is
specified, the rows are updated in the order that is specified. The
LIMIT clause places a limit on the number of rows that can be updated.

For the multiple-table syntax, UPDATE updates rows in each table named
in table_references that satisfy the conditions. In this case, ORDER BY
and LIMIT cannot be used.

where_condition is an expression that evaluates to true for each row to
be updated. For expression syntax, see
http://dev.mysql.com/doc/refman/5.5/en/expressions.html.

table_references and where_condition are is specified as described in
http://dev.mysql.com/doc/refman/5.5/en/select.html.

You need the UPDATE privilege only for columns referenced in an UPDATE
that are actually updated. You need only the SELECT privilege for any
columns that are read but not modified.

The UPDATE statement supports the following modifiers:

o With the LOW_PRIORITY keyword, execution of the UPDATE is delayed
  until no other clients are reading from the table. This affects only
  storage engines that use only table-level locking (such as MyISAM,
  MEMORY, and MERGE).

o With the IGNORE keyword, the update statement does not abort even if
  errors occur during the update. Rows for which duplicate-key
  conflicts occur are not updated. Rows for which columns are updated
  to values that would cause data conversion errors are updated to the
  closest valid values instead.

URL: http://dev.mysql.com/doc/refman/5.5/en/update.html

mysql> SELECT CURRENT_TIME();(查看当前时间)
+----------------+
| CURRENT_TIME() |
+----------------+
| 13:40:58       |
+----------------+
1 row in set (0.00 sec)

mysql> HELP LOCK(查看锁语法帮助)
Name: 'LOCK'
Description:
Syntax:
LOCK TABLES(表加锁)
    tbl_name [[AS] alias] lock_type
    [, tbl_name [[AS] alias] lock_type] ...

lock_type:(锁类型)
    READ [LOCAL](READ读锁)
  | [LOW_PRIORITY] WRITE(WRITE写锁)

UNLOCK TABLES(解锁)

MySQL enables client sessions to acquire table locks explicitly for the
purpose of cooperating with other sessions for access to tables, or to
prevent other sessions from modifying tables during periods when a
session requires exclusive access to them. A session can acquire or
release locks only for itself. One session cannot acquire locks for
another session or release locks held by another session.

Locks may be used to emulate transactions or to get more speed when
updating tables. This is explained in more detail later in this
section.

LOCK TABLES explicitly acquires table locks for the current client
session. Table locks can be acquired for base tables or views. You must
have the LOCK TABLES privilege, and the SELECT privilege for each
object to be locked.

For view locking, LOCK TABLES adds all base tables used in the view to
the set of tables to be locked and locks them automatically. If you
lock a table explicitly with LOCK TABLES, any tables used in triggers
are also locked implicitly, as described in
http://dev.mysql.com/doc/refman/5.5/en/lock-tables-and-triggers.html.

UNLOCK TABLES explicitly releases any table locks held by the current
session. LOCK TABLES implicitly releases any table locks held by the
current session before acquiring new locks.

Another use for UNLOCK TABLES is to release the global read lock
acquired with the FLUSH TABLES WITH READ LOCK statement, which enables
you to lock all tables in all databases. See [HELP FLUSH]. (This is a
very convenient way to get backups if you have a file system such as
Veritas that can take snapshots in time.)

URL: http://dev.mysql.com/doc/refman/5.5/en/lock-tables.html

mysql> USE jiaowu;(修改默认数据库为jiaowu)
Database changed
mysql> SHOW TABLES;(显示当前数据库表)
+------------------+
| Tables_in_jiaowu |
+------------------+
| courses          |
| scores           |
| sct              |
| students         |
| tutors           |
+------------------+
5 rows in set (0.01 sec)

mysql> LOCK TABLES tutors READ;(将tutors表加锁为读锁)
Query OK, 0 rows affected (0.00 sec)

测试:打开另外一个mysql会话查询锁定的表,可以查询;

mysql> SELECT * FROM tutors;(查询tutors表的所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   31 |
|  13 | Xuzhu        | M      |   26 |
|  14 | LingHuchong  | M      |   22 |
|  15 | stu1         | F      |   23 |
+-----+--------------+--------+------+
15 rows in set (0.00 sec)

mysql> INSERT INTO tutors (Tname,Gender,Age) VALUES ('jerry','M',50);(向tutors表的Tname、Gender、Age字段插入数据)

提示:命令卡住了,等待别人释放锁,这是我们手动加的锁,其实大多数情况下MySQL自己内部就会维持锁了,我们没必要手动去加锁的,就算两个用户同时读写,在有些特殊的场景下我
们才需要手动持有锁,在实现数据库的无人备份的时候;

mysql> UNLOCK TABLES;(解锁所有表)
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO tutors (Tname,Gender,Age) VALUES ('jerry','M',50);
Query OK, 1 row affected (5 min 17.59 sec)

提示:解锁后,插入命令立即执行结束,执行了5分17秒;

mysql> SHOW GLOBAL VARIABLES LIKE '%iso%';(查看全局变量以任意长度任意字符开始中间iso任意长度任意字符结尾)
+---------------+-----------------+
| Variable_name | Value           |
+---------------+-----------------+
| tx_isolation  | REPEATABLE-READ |
+---------------+-----------------+
1 row in set (0.00 sec)

提示:默认是REPEATABLE-READ隔离级别;

mysql> SET tx_isolation='READ-UNCOMMITTED';(修改MySQL会话变量tx_isolation隔离级别为READ-UNCOMMITTED)
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@tx_isolation;(查看tx_isolation变量值)
+------------------+
| @@tx_isolation   |
+------------------+
| READ-UNCOMMITTED |
+------------------+
1 row in set (0.00 sec)

多事务同时执行,彼此之间互相不影响方式进行并发;

  事务之间交互:

    通过数据集

事务:CPU, I/O 多项操作要作为一个处理单元来进行对待,它们要么同时都执行,要么同时都不执行;

  RDBMS,

    ACID:

      Automicity: 原子性,事务锁引起的数据库操作,要么都完成,要么都不执行,一个事务可能有个执行单元,或者多个执行语句,这些语句要么同时都完成,要么同时都不完成,要把他们当作一个整体来看待,事务的所有操作在数据库当中要么完全的反映出来,要么完全的都不反映;

      Consistency: 一致性,我们的数据库一定要从一个状态而且这种状态是平稳转换的,当事务执行结束之后我们的整个数据库的状态是没有改变的,也就意味着事务前的总和和事务后的总和是一致的,这个一致性指的是事务在隔离状态下执行的,它跟我们的隔离性有关系,不然两个事务交差执行仍然会导致你的事务本身可能没问题,但仍然导致由于跟其它事务的交差执行,导致事务结果处于不一致状态,这种可能性仍然会发生,A(3000) --> B(2000)

      Isolation: 隔离性,为了尽可能提高服务器的并发能力,一般允许多个事务同时执行,每一个事务都可能涉及到一定的CPU操作和I/O操作,在执行I/O操作的时候我们的CPU是空闲的,这时候让CPU做一些别的事情这样尽可能提高了我们资源的利用率,所以这就是为什么要允许事务并发执行的概念,多事务同时执行就可能产生问题,因为事务和事务之间可能会交互,它又不是进程,不像进程之间可以实现进程间通信,通过I/O操作之间的数据集交互,比如第一个事务修改了数据,第二个事务能看到,这样就能交互了,而数据集本身会随时发生改变了,所以这样交互可能会给事务带来额外影响,因此在一定程度上来讲我们可能需要事务彼此之间进行隔离,以免数据集在交互的时候产生中间的不一致状态,因此并法执行不能是简单的并发,一定是让它们在并发的时候能够彼此之间不相影响的进行并发,我操作的事务集极可能不跟你的事务集交互,但是我们只要执行两个事务,两个事务如果操作了同一张表或者同一个表中的某些行的话就有可能要交互,由此我们数据库必须要有一种机制来保证他们彼此之间在交互的时候不影响彼此,我们要提供隔离线,这种隔离线说白了是靠数据库内部事务调度来实现的,两个事务看上去都能执行,但这个执行次序是一个事务不会影响另一个事务,一定是事务调度的时候让彼此之间不受影响,或者影响尽可能降到最低;

        事务调度,事务之间影响最小

        MVCC:多版本并发控制,基于时间,基于快照来实现;

      Durability: 持久性,一旦事务成功完成,无论任何情况任何意味发生都必须保证这个事务是可得到的,账户转账是持久,是不能再次发生变化的,所以系统必须保证任何故障都不会引起事务出现意味情况,表现出不一致性;

        1、事务提交之前就已经写出数据至持久性存储;

        2、结合事务日志完成;

          事务日志: 顺序I/O

          数据文件: 随机I/O

  事务的状态:

    活动的: active

    部分提交的: 最后一条语句执行后

    失败的:

    终止的:

    提交的: 事务一旦提交就无法撤销;

事务: 并发执行

  1、提高吞吐量和资源利用率

  2、减少等待时间

事务调度:

  可恢复调度

  无级联调度

隔离级别:

  READ UNCOMITTED 读未提交

  READ COMMITTED 读提交

  REPEATABLE READ 可重读,MySQL默认;

  SERIALIZABLE 串行的

并发控制依赖的技术手段:

  锁

  时间戳

  多版本和快照隔离

饿死:

死锁:


SQL, ODBC

START TRANSACTION 启动一个事务;

  SQL

  SQL
COMMIT: 提交,事务完成;

ROLLBAXK: 回滚,不再执行;

如果没有明确启动事务:

  autocommit: 能够实现自动提交,所以每一句都会直接提交;

  建议:明确使用事务,并且关闭自动提交,这是MySQL优化的一种策略;

一旦关闭autocommit自动提交应该明确使用事务,任何操作之前应该使用START TRANSACTION启动事务,或者任何一批操作之前,如果不明确启动那么整个语句统统被当作一个事务;

保存点: SAVEPOINT sid(sid标识符,不能使用数字)

回滚到保存点: ROOLBACK TO sid(sid标识符,不能使用数字)

事务: 100,

80, 75(假如启动很大事务,这个事务里面有100个操作,执行到第80的时候发现第75个错了,撤销,一撤销80个操作全撤了,因为后面20个还没写,这时候怎么办,保存点就有作用了,比如每10个语句保存一次,它可以记录下来你保存的那个位置,将来我们撤销的时候可以只撤回到指定的保存点的)

事务隔离级别对事务影响:

mysql> START TRANSACTION;(启动事务)
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM tutors;(查询tutors表所有字段的数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   31 |
|  13 | Xuzhu        | M      |   26 |
|  14 | LingHuchong  | M      |   22 |
|  15 | stu1         | F      |   23 |
|  16 | stu1         | F      |   23 |
|  18 | jerry        | M      |   50 |
+-----+--------------+--------+------+
17 rows in set (0.00 sec)

mysql> DELETE FROM tutors WHERE Tname LIKE 'stu%';(删除tutors表中Tname字段stu开头的行)
Query OK, 2 rows affected (0.00 sec)

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   31 |
|  13 | Xuzhu        | M      |   26 |
|  14 | LingHuchong  | M      |   22 |
|  18 | jerry        | M      |   50 |
+-----+--------------+--------+------+
15 rows in set (0.00 sec)

提示:如果这时候发现删除错误,可以回滚事务;

mysql> ROLLBACK;(回滚事务)
Query OK, 0 rows affected (0.01 sec)

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   31 |
|  13 | Xuzhu        | M      |   26 |
|  14 | LingHuchong  | M      |   22 |
|  15 | stu1         | F      |   23 |
|  16 | stu1         | F      |   23 |
|  18 | jerry        | M      |   50 |
+-----+--------------+--------+------+
17 rows in set (0.00 sec)

提示:stu1又恢复回来;

mysql> START TRANSACTION;(启动事务)
Query OK, 0 rows affected (0.01 sec)

mysql> SELECT * FROM tutors;(查询tutors表中所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   31 |
|  13 | Xuzhu        | M      |   26 |
|  14 | LingHuchong  | M      |   22 |
|  15 | stu1         | F      |   23 |
|  16 | stu1         | F      |   23 |
|  18 | jerry        | M      |   50 |
+-----+--------------+--------+------+
17 rows in set (0.00 sec)

mysql> DELETE FROM tutors WHERE Tname LIKE 'stu%';(删除tutors表stu开头的行)
Query OK, 2 rows affected (0.00 sec)

mysql> COMMIT;(提交事务)
Query OK, 0 rows affected (0.01 sec)

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   31 |
|  13 | Xuzhu        | M      |   26 |
|  14 | LingHuchong  | M      |   22 |
|  18 | jerry        | M      |   50 |
+-----+--------------+--------+------+
15 rows in set (0.00 sec)

mysql> ROLLBACK;(回滚)
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM tutors;(查询tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   31 |
|  13 | Xuzhu        | M      |   26 |
|  14 | LingHuchong  | M      |   22 |
|  18 | jerry        | M      |   50 |
+-----+--------------+--------+------+
15 rows in set (0.00 sec)

提示:一个事务一旦提交以后就不能再撤销了;

mysql> SELECT @@autocommit;(查看自动提交变量)
+--------------+
| @@autocommit |
+--------------+
|            1 |
+--------------+
1 row in set (0.00 sec)

提示:autocommit表示是不是开启mysql的自动提交事务的功能,每个语句执行结束之后它都会自动提交,对于事务性存储引擎来讲像InnoDB如果我们没有明确使用START TRANSACTION;

mysql> DELETE FROM tutors WHERE Tname='Xuzhu';(删除tutors表条件Tname等于Xuzhu的行)
Query OK, 1 row affected (0.00 sec)

mysql> ROLLBACK;(撤销事务)
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   31 |
|  14 | LingHuchong  | M      |   22 |
|  18 | jerry        | M      |   50 |
+-----+--------------+--------+------+
14 rows in set (0.00 sec)

提示:如果我们没有显示启动事务,那就能控制实现autocommit自动提交

mysql> SET autocommit=0;(修改自动提交参数的值为0,关闭自动提交)
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@autocommit;(查看自动提交autocommit参数值)
+--------------+
| @@autocommit |
+--------------+
|            0 |
+--------------+
1 row in set (0.00 sec)

mysql> DELETE FROM tutors WHERE Tname='HuFei';
Query OK, 1 row affected (0.00 sec)

mysql> ROLLBACK;(回滚)
Query OK, 0 rows affected (0.01 sec)

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   31 |
|  14 | LingHuchong  | M      |   22 |
|  18 | jerry        | M      |   50 |
+-----+--------------+--------+------+
14 rows in set (0.00 sec)

提示:删除字段Tname的HuFei没有提交;

mysql> HELP SAVEPOINT;(查看保存点的帮助)
Name: 'SAVEPOINT'
Description:
Syntax:
SAVEPOINT identifier(identifier标识符)
ROLLBACK [WORK] TO [SAVEPOINT] identifier(回滚到保存点,identifier保存点)
RELEASE SAVEPOINT identifier

InnoDB supports the SQL statements SAVEPOINT, ROLLBACK TO SAVEPOINT,
RELEASE SAVEPOINT and the optional WORK keyword for ROLLBACK.

URL: http://dev.mysql.com/doc/refman/5.5/en/savepoint.html

mysql> START TRANSACTION;(启动事务)
Query OK, 0 rows affected (0.00 sec)

mysql> DELETE FROM tutors WHERE TID=18;(删除表tutors条件TID等于18的行)
Query OK, 1 row affected (0.01 sec)

mysql> SAVEPOINT ab;(启动保存点,标识符为ab)
Query OK, 0 rows affected (0.01 sec)

mysql> DELETE FROM tutors WHERE TID=14;(删除表tutors条件TID等于14的行)
Query OK, 1 row affected (0.00 sec)

mysql> SAVEPOINT ac;(启动保存点,标识符ac)
Query OK, 0 rows affected (0.00 sec)

mysql> DELETE FROM tutors WHERE TID=12;(删除tutors表条件TID等于12的行)
Query OK, 1 row affected (0.00 sec)

mysql> SAVEPOINT ad;(启动保存点,标识符ad)
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM tutors;(查看表tutors所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
+-----+--------------+--------+------+
11 rows in set (0.00 sec)

提示:三个删除的行都没有了,现在想要不删除第12个怎么办;

mysql> ROLLBACK TO ac;(还原保存点到ac标识符)
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   31 |
+-----+--------------+--------+------+
12 rows in set (0.00 sec)

提示:TID等于12的行恢复回来了,回到保存点,只是回到保存点之前的状态;

启动两个MySQL会话,而后把两个MySQL会话的默认隔离级别都设定为第一个叫做READ UNCOMITTED读未提交,而后启动事务以后,看第一个事务的操作会不会影响第二个事务的操作,或
者它们在多大程度上影响第二个事务操作:

第一个MySQL会话:

mysql> SELECT @@tx_isolation;(查看会话变量tx_isolation隔离级别的值)
+-----------------+
| @@tx_isolation  |
+-----------------+
| REPEATABLE-READ |
+-----------------+
1 row in set (0.00 sec)

mysql> SET tx_isolation='READ-UNCOMMITTED';(设置会话变量隔离级别为读未提交)
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@tx_isolation;(查看会话变量隔离级别的值)
+------------------+
| @@tx_isolation   |
+------------------+
| READ-UNCOMMITTED |
+------------------+
1 row in set (0.00 sec)

第二个MySQL会话:

mysql> SELECT @@tx_isolation;(查看会话变量隔离级别的值)
+------------------+
| @@tx_isolation   |
+------------------+
| READ-UNCOMMITTED |
+------------------+
1 row in set (0.00 sec)

第一个MySQL会话:

mysql> START TRANSACTION;(启动事务)
Query OK, 0 rows affected (0.00 sec)

第二个MySQL会话:

mysql> START TRANSACTION;(启动事务)
Query OK, 0 rows affected (0.00 sec)

第一个MySQL会话:

mysql> SELECT * FROM tutors;(查看tutors表所有字段的数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   31 |
+-----+--------------+--------+------+
12 rows in set (0.00 sec)

mysql> UPDATE tutors SET Age=50 WHERE TID=12;(更新表tutors数据的Age字段为50条件TID等于12的数据)
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SELECT * FROM tutors;(查tutors表所有字段所有数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   50 |
+-----+--------------+--------+------+
12 rows in set (0.00 sec)

第二个MySQL会话:

mysql> SELECT * FROM tutors;
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   50 |
+-----+--------------+--------+------+
12 rows in set (0.00 sec)

提示:TID为12的Age字段变为50,第二个MySQL会话的事务可以看到第一个MySQL会话执行的语句,READ-UNCOMMITTED读未提交,别人没有提交的我们都看的到,过一会别人撤销了,不执行了;

第一个MySQL会话:

mysql> ROLLBACK;(撤销)
Query OK, 0 rows affected (0.01 sec)

第二个MySQL会话:

mysql> SELECT * FROM tutors;
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   31 |
+-----+--------------+--------+------+
12 rows in set (0.00 sec)

提示:TID为12的Age字段变为31,幻影问题,自己内部两次同时读一个数据不一样;

mysql> COMMIT;(提交事务)
Query OK, 0 rows affected (0.00 sec)

READ COMMITTED 读提交的影响:

第一个MySQL会话:

mysql> SET tx_isolation='READ-COMMITTED';(更改会话变量tx_isolation为读提交)
Query OK, 0 rows affected (0.00 sec)

第二个MySQL会话:

mysql> SET tx_isolation='READ-COMMITTED'; (更改会话变量tx_isolation为读提交)
Query OK, 0 rows affected (0.00 sec)

mysql> START TRANSACTION;(启动事务)
Query OK, 0 rows affected (0.00 sec)

第一个MySQL会话:

mysql> START TRANSACTION;(启动事务)
Query OK, 0 rows affected (0.00 sec)

mysql> UPDATE tutors SET Age=50 WHERE TID=12;(更新tutors表Age等于50条件TID等于12)
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   50 |
+-----+--------------+--------+------+
12 rows in set (0.00 sec)

提示:TID字段为12的Age字段改为50;

第二个MySQL会话:

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   31 |
+-----+--------------+--------+------+
12 rows in set (0.00 sec)

提示:别人尚未提交,现在TID为12的Age字段值为31,这叫读提交,别人未提交我们就读不到,别人一提交就可以看得到了;

第一个MySQL会话:

mysql> COMMIT;(提交)
Query OK, 0 rows affected (0.01 sec)

第二个MySQL会话:

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   50 |
+-----+--------------+--------+------+
12 rows in set (0.01 sec)

提示:对方提交了,TID字段为12的Age字段为50,所有在一个事务中仍然看到两次不一样,但是只不过是别人提交以后才能看到而已,仍然会产生幻影问题;

REPEATABLE-READ可重读影响:

第一个MySQL会话:

mysql> SET tx_isolation='REPEATABLE-READ';(更改当前会话变量tx_isolation值为可重读)
Query OK, 0 rows affected (0.01 sec)

第二个MySQL会话:

mysql> SET tx_isolation='REPEATABLE-READ';(更改当前会话变量tx_isaolation值为可重读)
Query OK, 0 rows affected (0.01 sec)

第一个MySQL会话:

mysql> START TRANSACTION;(启动事务)
Query OK, 0 rows affected (0.00 sec)

第二个MySQL会话:

mysql> START TRANSACTION;(启动事务)
Query OK, 0 rows affected (0.00 sec)

第一个MySQL会话:

mysql> UPDATE tutors SET Age=80 WHERE TID=12;(更新tutors表Age字段为80条件TID等于12)
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   80 |
+-----+--------------+--------+------+
12 rows in set (0.00 sec)

提示:TID字段为12的Age字段的值为80;

第二个MySQL会话:

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   50 |
+-----+--------------+--------+------+
12 rows in set (0.01 sec)

提示:TID字段为12的Age字段的值为50,因为它比READ COMMITTED级别更高;

第一个MySQL会话:

mysql> COMMIT;(提交事务)
Query OK, 0 rows affected (0.02 sec)

提示:提交之后数据就是永久的;

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   80 |
+-----+--------------+--------+------+
12 rows in set (0.00 sec)

第二个MySQL会话:

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   50 |
+-----+--------------+--------+------+
12 rows in set (0.01 sec)

提示:TID字段为12的Age字段的值为50,可重读,就算别人提交我们这边仍然看到的是同一个值,只要自己的事务不提交;

mysql> COMMIT;(提交事务)
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   80 |
+-----+--------------+--------+------+
12 rows in set (0.00 sec)

提示:事务之间看到的都是同一个值,事务提交看到的是最终值,可重读仍然会产生幻影问题,至少提交前和提交后不一样,我们自己没做任何修改就看了两次不一样;

SERIALIZABLE 串行影响:

第一个MySQL会话:

mysql> SET tx_isolation='SERIALIZABLE';(设置会话变量tx_isolation值为SERIALIZABLE)
Query OK, 0 rows affected (0.00 sec)

第二个MySQL会话:

mysql> SET tx_isolation='SERIALIZABLE';(设置会话变量tx_isolation值为SERIALIZABLE)
Query OK, 0 rows affected (0.00 sec)

第一个MySQL会话:

mysql> START TRANSACTION;(启动事务)
Query OK, 0 rows affected (0.00 sec)

第二个MySQL会话:

mysql> START TRANSACTION;(启动事务)
Query OK, 0 rows affected (0.00 sec)

第一个MySQL会话:

mysql> UPDATE tutors SET Age=70 WHERE TID=12;(更新tutors表Age字段数据为70条件TID等于12)
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

第二个MySQL会话:

mysql> SELECT * FROM tutors;(查看tutors表所有字段数据)
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction(锁等待超时,请尝试重启启动事务)

提示:SELECT * FROM tutors语句卡住

第一个MySQL会话:

mysql> COMMIT;(提交事务)
Query OK, 0 rows affected (0.00 sec)

第二个MySQL会话:

mysql> SELECT * FROM tutors;
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   70 |
+-----+--------------+--------+------+
12 rows in set (41.14 sec)

提示:第一个MySQL的会话提交事务以后第二个MySQL会话的查询才结束,而且值发生改变;

mysql> COMMIT;(提交事务)
Query OK, 0 rows affected (0.00 sec)

第一个MySQL会话:

mysql> START TRANSACTION;(启动事务)
Query OK, 0 rows affected (0.01 sec)

第二个MySQL会话:

mysql> START TRANSACTION;(启动事务)
Query OK, 0 rows affected (0.01 sec)

第一个MySQL会话:

mysql> SELECT * FROM tutors;(查询tutors表所有字段属性)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   20 |
+-----+--------------+--------+------+
12 rows in set (0.00 sec)

mysql> UPDATE tutors SET Age=25 WHERE TID=12;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SELECT * FROM tutors;(查询tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   25 |
+-----+--------------+--------+------+
12 rows in set (0.00 sec)

第二个MySQL会话:

mysql> SELECT * FROM tutors;(查询tutors表所有字段数据)
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction(锁等待超时,请尝试重启启动事务)

mysql> START TRANSACTION;(启动事务)
Query OK, 0 rows affected (0.01 sec)

mysql> SELECT * FROM tutors;(查询tutors表所有字段数据)

第一个MySQL会话:

mysql> COMMIT;(提交)
Query OK, 0 rows affected (0.01 sec)

第二个MySQL会话:

mysql> SELECT * FROM tutors;(查询tutors表所有字段数据)
+-----+--------------+--------+------+
| TID | Tname        | Gender | Age  |
+-----+--------------+--------+------+
|   1 | HongQigong   | M      |   93 |
|   2 | HuangYaoshi  | M      |   63 |
|   3 | Miejueshitai | F      |   72 |
|   4 | OuYangfeng   | M      |   76 |
|   5 | YiDeng       | M      |   90 |
|   6 | YuCanghai    | M      |   56 |
|   7 | Jinlunfawang | M      |   67 |
|   8 | HuYidao      | M      |   42 |
|   9 | NingZhongze  | F      |   49 |
|  10 | Tom          | F      |   30 |
|  11 | DingDian     | M      |   25 |
|  12 | HuFei        | M      |   25 |
+-----+--------------+--------+------+
12 rows in set (28.23 sec)

提示:一旦使用了串型话事务之间的隔离效果特别好,绝对不会看到中间提交的结果,而每次看到的结果都是前后一致的,但事务并发不能进行,所以事务隔离级别越高,事务安全性越好,
但是并发能力越差,在以后实际中如果对事务安全要求不是很高,尽可能降低事务隔离级别;

User Mangement(用户管理)

MySQL

  用户: 获取资源或服务的凭证,MySQL的用户类似于vsftpd的虚拟用户,它只是MySQL的用户,跟操作系统没有关系,我们是不能拿着MySQL的用户登录操作系统的,同样也没有办法通过操作系统用户访问MySQL;

  密码: 只有某个授权使用用户才能获取,也是确保授权能够真正实现其功能的手段和工具,对MySQL而言密码是使用MySQL独有的加密机制进行加密的,默认使用password()函数,这个加密机制和linux上用户密码加密机制也是不相同的,更不能拿来视图登录操作系统;

  用户名@主机: 用户只能通过对应的主机才能访问MySQL服务,除此之外MySQL账户没有其它作用;

帐号: 认证

权限:

  授权

在MySQL服务器上用户的帐号和密码等信息是保存在安装完MySQL服务器并启动起来以后叫做MySQL数据当中的多个表中实现的,这些表包括user、db、host、tables_priv、columns_priv以及procs_priv组成,MySQL服务器在启动的时候会读取这6张表并在内存中生成授权表,所以这几个文件是直接加载进内存中的,以后后续的任何用户登录及其访问权限的检查都通过检查这6张表来实现,而检查的过程不再是通过访问磁盘上的表,而是访问内存中所生成的结构信息来完成,之所以要放在内存中,因为任何一个SQL语句执行都有可能要查询授权表,因为任何一个SQL语句在执行的时候我们都需要去检查用户是否有访问对应资源的权限的,因此为了加速这个过程MySQL将所有的授权表读进内存进行管理;

用户和权限管理

Information about account privileges is stored in the user, db, host, tables_priv, columns_rpiv, and procs_priv tables in the mysql_database. The MySQL server reads the contents of these tables into memory when it starts and reloads them under the circumstances.Access-control decisions are based on the in-memory copies of the grant tables.

user: contains user accounts, global privileges, and other non-privilege columns.(包含用户帐号,全局权限,以及其它的非权限字段)

user: 用户帐号、全局权限

db: Contains database-level privileges.(数据库级别权限定义)

db: 库级别权限

host: Obsolete.(废弃)

host: 废弃

tables_priv: Contains table-level privileges.(表级别权限)

columns_priv: Contains column-level privileges.(列级别权限)

procs_priv: Contains stored procedure and function privileges.(存储过程和存储函数相关权限)

proxies_priv: Contains proxy-user privileges.(代理用户权限)

There are serveral destinctions between the way user names and passwords are used by MySQL and the way they are used by your operating system:

  User names, as used by MySQL for authentication purposes, have nothing to do with user names (login names) as used by Windows or Unix.

  MySQL user names can be up to 16 characters long.

  The server uses MySQL passwords stored in the user table to authenticate client connections using MySQL native authentication (against passwords stored in the mysql.user table).

  MySQL encrypts passwords stored in the user table using its own algorithm. This encryption is the same as that implemented by the PASSWORD() SQL function but differs from that used during the Unix login process.

  It is possible to connect to the server regardless of character set settings if the user name and password contain only ASCII characters.

用户帐号:

  用户名@主机

    用户名16字符以内

    主机:

      主机名: www.magedu.com, mysql

      IP: 172.16.10.177

      网络地址:

        172.16.0.0/255.255.0.0

    通配符: %(任意长度任意字符), _(单个任意字符)

      172.16.%.%

      %.magedu.com(这个域内所有主机)

  --skip-name-resolve 为了验证主键的来源是否合法,一般MySQL需要反解用户的主机名,或者解析用户主机名,在很多时候这需要相当消耗时间,为了加速MySQL服务器性能,而且访问MySQL也不需要它通过主机名来认证的话,禁用一切基于主机名的方式进行授权,启动MySQL服务器的时候可以使用--skip-name-resolve选项略过名称解析,每一次用户再来验证用户名的时候就不用再解析主机名了,在一定程度这会大大用户连接时候的速度;

权限级别:

  全局级别: SUPER、

  库级别

  表级别: DELETE, ALTER, TRGGER,

  列级别: SELECT, INSERT, UPDATE

  存储过程和存储函数

字段级别:

临时表: 内存表,速度快,临时

  heap: 16MB

触发器: 完成主动数据库创建

  INSERT, DELETE, UPDATE

    user: log

创建用户:

CREATE USER username@host [IDENTFIED BY 'password'] 创建用户,这样创建的用户只有USAGE权限和简单SHOW DATABASES这样权限;

GRANT 授权,只不过授权的时候如果用户帐号不存在会自动调用CREATE USER去创建用户帐号的;

GRANT ALL PRIVILEGES ON [object_type] db.* TO username@'%';(db.*不光可以表示表,还可以这个数据库内的所有存储过程或存储函数)

TABLE 表

FUNCTION 函数

PROCEDURE 过程

GRANT EXCUTE ON FUNCTION db.abc TO username@'%';(在db库abc存储函数授权username@'%'具有执行权限)

INSERT INTO mysql.user 直接插入信息到mysql数据库的user表中,必须刷新授权表;

mysql> FLUSH PRIVILEGES;(刷新授权表)

SHOW GRANTS FOR 'username@host' 查看某个用户相关授权信息;

with_option:(资源使用限定)

  GRANT OPTION(可以将自己的授权授予别人)

  | MAX_QUERIES_PER_HOUR count(每小时最多允许发起多少查询请求,count数值,可以限定用户连接进来的资源使用权限,不做限定将count设置为0)

  | MAX_UPDATES_PER_HOUR count(每小时只允许使用几次UPDATE)

  | MAX_CONNECTIONS_PER_HOUR count(每小时只允许发起多少个新的连接请求)

  | MAX_USER_CONNECTIONS count(某个用户帐号最多允许连接几次)

--skip-gran-tables 跳过授权表

--skip-name-resolve 跳过名次解析,解决资源

--skip-networking 跳过网络,不允许通过网络连接mysql数据库

DROP USER 'username'@'host' 删除用户

RENAME USER old_name TO new_name 用户重命名

REVOKE 取消授权

MySQL管理员密码恢复操作:

启动mysqld_safe时传递两个参数:

  --skip-grant-tables

  --skip-networking

  通过更新授权表方式直接修改其密码,然后移除两个选项重启服务器,就能完成找回管理员密码;

CREATE: 用来创建库、表、或者索引,一个CREATE命令可以授权用户创建库、表、索引权限;

DROP: 用来删除库、表、视图;

GRANT OPTION: 一个用户在获得授权以后能不能将自己获得的授权再次授予其它用户,

INSERT: 用在表和字段;

SELECT: 用在表和字段;

UPDATE: 用在表和字段;

DELETE: 用在表级别;

REFERENCES: 用在库和表级别,引用,能够创建外键约束;

EVENT: 创建事件调度器,库级别;

CREATE TABLESPACE: 创建表空间,服务器管理级别权限;

CREAtE USER: 创建用户,服务器管理级别权限;

PROCESS: 查看进程列表,服务器管理级别权限;

PROXY: 代理服务,代理用户创建,服务器管理级别权限;

RELOAD: 重载授权表,服务器管理级别权限;

REPLICATION CLIENT: 用于复制的权限,服务器管理级别权限;

REPLICATION SLAVE: 用于复制的权限,服务器管理级别权限;

SHOW DATABASES: 服务器管理级别权限;

SHUTDOWN: 关闭服务,服务器管理级别权限;

SUPER: 管理权限,改变主服务器指向,特殊管理权限,服务器管理级别权限;

ALL [PRIVILECES]: 服务器管理级别权限;

USAGE: 没有任何权限,仅允许用户MySQL服务器连接到MySQL上,能够通过服务器管理级别权限;

FILE: 访问服务器上的文件,可以将文件数据直接导入表中,或者将表中数据备份到文件中;

ALTER ROUTING: 修改存储过程或存储函数;

CREATE ROUTING: 创建存储历程,存储过程或存储函数;

EXECUTE: 执行存储过程或存储函数;

CREATE VIEW: 创建视图

SHOW VIEW: 显示视图

CREATE TEMPORARY_TABLES: 创建临时表;

TRIGGER: 触发器;

ALTER: 修改表

DELETE: 删除表中的数据;

INDEX: 给表创建索引;

[root@localhost ~]# mysql(连接mysql服务器)
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 32
Server version: 5.5.28-log Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql> USE mysql;(修改默认数据库为mysql)
Database changed

mysql> SELECT * FROM db\G(查看db数据库所有字段数据,\G竖状显示)
*************************** 1. row ***************************
                 Host: %(主机)
                   Db: test
                 User: 
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          Delete_priv: Y
          Create_priv: Y
            Drop_priv: Y
           Grant_priv: N
      References_priv: Y
           Index_priv: Y
           Alter_priv: Y
Create_tmp_table_priv: Y
     Lock_tables_priv: Y
     Create_view_priv: Y
       Show_view_priv: Y
  Create_routine_priv: Y
   Alter_routine_priv: N
         Execute_priv: N
           Event_priv: Y
         Trigger_priv: Y
*************************** 2. row ***************************
                 Host: %
                   Db: test\_%(以test开头后面跟_下划线后面跟任意长度任意字符的库,\转义)
                 User: 
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          Delete_priv: Y
          Create_priv: Y
            Drop_priv: Y
           Grant_priv: N
      References_priv: Y
           Index_priv: Y
           Alter_priv: Y
Create_tmp_table_priv: Y
     Lock_tables_priv: Y
     Create_view_priv: Y
       Show_view_priv: Y
  Create_routine_priv: Y
   Alter_routine_priv: N
         Execute_priv: N
           Event_priv: Y
         Trigger_priv: Y
2 rows in set (0.01 sec)

提示:这里只授权了两个库,一个是test,一个是test\_%的两类库;

mysql> HELP CREATE USER;(查看创建用户帮助)
Name: 'CREATE USER'
Description:
Syntax:
CREATE USER user_specification(创建用户,USER后面用户名加主机)
    [, user_specification] ...

user_specification:
    user
    [
        IDENTIFIED BY [PASSWORD] 'password'
      | IDENTIFIED WITH auth_plugin [AS 'auth_string']
    ]

The CREATE USER statement creates new MySQL accounts. To use it, you
must have the global CREATE USER privilege or the INSERT privilege for
the mysql database. For each account, CREATE USER creates a new row in
the mysql.user table and assigns the account no privileges. An error
occurs if the account already exists.

Each account name uses the format described in
http://dev.mysql.com/doc/refman/5.5/en/account-names.html. For example:

CREATE USER 'jeffrey'@'localhost' IDENTIFIED BY 'mypass';

If you specify only the user name part of the account name, a host name
part of '%' is used.

The user specification may indicate how the user should authenticate
when connecting to the server:

o To enable the user to connect with no password (which is insecure),
  include no IDENTIFIED BY clause:

CREATE USER 'jeffrey'@'localhost';

  In this case, the account uses built-in authentication and clients
  must provide no password.

o To assign a password, use IDENTIFIED BY with the literal plaintext
  password value:

CREATE USER 'jeffrey'@'localhost' IDENTIFIED BY 'mypass';

  The account uses built-in authentication and clients must match the
  given password.

o To avoid specifying the plaintext password if you know its hash value
  (the value that PASSWORD() would return for the password), specify
  the hash value preceded by the keyword PASSWORD:

CREATE USER 'jeffrey'@'localhost'
IDENTIFIED BY PASSWORD '*90E462C37378CED12064BB3388827D2BA3A9B689';

  The account uses built-in authentication and clients must match the
  given password.

o To authenticate the account using a specific authentication plugin,
  use IDENTIFIED WITH, where auth_plugin is the plugin name. It can be
  an unquoted name or a quoted string literal. 'auth_string' is an
  optional quoted string literal to pass to the plugin. The plugin
  interprets the meaning of the string, so its format is plugin
  specific. Consult the documentation for a given plugin for
  information about the authentication string values it accepts.

CREATE USER 'jeffrey'@'localhost'
IDENTIFIED WITH my_auth_plugin;

  For connections that use this account, the server invokes the named
  plugin and clients must provide credentials as required for the
  authentication method that the plugin implements. If the server
  cannot find the plugin, either at account-creation time or connect
  time, an error occurs. IDENTIFIED WITH can be used as of MySQL 5.5.7.

The IDENTIFIED BY and IDENTIFIED WITH clauses are mutually exclusive,
so at most one of them can be specified for a given user.

For additional information about setting passwords, see
http://dev.mysql.com/doc/refman/5.5/en/assigning-passwords.html.

URL: http://dev.mysql.com/doc/refman/5.5/en/create-user.html

mysql> CREATE USER cactiuser@'%' IDENTIFIED BY 'cactiuser';(创建用户cactiuser密码cactiuser允许通过所有主机访问)
Query OK, 0 rows affected (0.00 sec)

提示:MySQL在服务器启动时候会自动读取6张表的权限到内存当中,而后在内存中维护的,像这里我们创建用户以后,这个用户最终保存到user表当中,那它怎么能够知道MySQL在内存
当中读取的信息会不会包含这个用户,所以为了保证MySQL每一次都能自动读取这个新创建的用户或者新建立的授权要使用FLUSH PRIVILEGE刷新,这就是通知MySQL服务器重读授权表,
并重新生效权限,事实上CREATE USER命令MySQL可以自动的触发FLUSH PRIVILEGE,只要使用CREATE USER创建,它会让你自动读取授权表;

mysql> SHOW GRANTS FOR cactiuser@'%';(查看cactiuser@'%'用户授权信息)
+----------------------------------------------------------------------------------------------------------+
| Grants for cactiuser@%                                                                                   |
+----------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'cactiuser'@'%' IDENTIFIED BY PASSWORD '*43DD7940383044FBDE5B177730FAD3405BC6DAD7' |
+----------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

提示:默认只有USAGE权限,创建会话连接到MySQL的过程,只允许登录;

测试:再打开一个Xshell通过ssh连接到linux主机,通过ucactiuser用户,密码ucactiuser连接MySQL数据库;

[root@localhost ~]# mysql -ucactiuser -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 33
Server version: 5.5.28-log Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql> SHOW DATABASES;(显示数据库)
+--------------------+
| Database           |
+--------------------+
| information_schema |
| test               |
+--------------------+
2 rows in set (0.00 sec)

提示:别的库都看不到,只能看到两个information_schema和test库,而且test是全局授权谁都可以用;

mysql> CREATE DATABASE cactidb;(创建数据库cactidb)
ERROR 1044 (42000): Access denied for user 'cactiuser'@'%' to database 'cactidb'

提示:没有权限创建数据库;

mysql> HELP GRANT(查看授权帮助) 
Name: 'GRANT'
Description:
Syntax:
GRANT
    priv_type [(column_list)](priv_type权限类型)
      [, priv_type [(column_list)]] ...
    ON [object_type] priv_level(某个对象,object_type对象类型,priv_level级别)
    TO user_specification [, user_specification] ...(user_specification用户,)
    [REQUIRE {NONE | ssl_option [[AND] ssl_option] ...}](ssl_option要求用户在远程连接的时候必须要使用ssl,NONE不需要任何属性,)
    [WITH with_option ...](额外授权属性)

GRANT PROXY ON user_specification
    TO user_specification [, user_specification] ...
    [WITH GRANT OPTION](一个用户在获得权限以后还可以把它的权限授予其它人)

object_type:(对象类型)
    TABLE (表)
  | FUNCTION(函数)
  | PROCEDURE(过程)

priv_level:(权限级别)
    * (所有库)
  | *.* (所有库的所有表)
  | db_name.* (某个库的所有表)
  | db_name.tbl_name(某个库的某张表)
  | tbl_name(某张特定表)
  | db_name.routine_name(某个库的存储过程或存储函数)

user_specification:
    user
    [
        IDENTIFIED BY [PASSWORD] 'password'
      | IDENTIFIED WITH auth_plugin [AS 'auth_string']
    ]

ssl_option:
    SSL(必须要使用SLL)
  | X509(必须要使用X509格式证书来实现建立SSL会话)
  | CIPHER 'cipher'
  | ISSUER 'issuer'
  | SUBJECT 'subject'

with_option:
    GRANT OPTION
  | MAX_QUERIES_PER_HOUR count
  | MAX_UPDATES_PER_HOUR count
  | MAX_CONNECTIONS_PER_HOUR count
  | MAX_USER_CONNECTIONS count

The GRANT statement grants privileges to MySQL user accounts. GRANT
also serves to specify other account characteristics such as use of
secure connections and limits on access to server resources. To use
GRANT, you must have the GRANT OPTION privilege, and you must have the
privileges that you are granting.

Normally, a database administrator first uses CREATE USER to create an
account, then GRANT to define its privileges and characteristics. For
example:

CREATE USER 'jeffrey'@'localhost' IDENTIFIED BY 'mypass';
GRANT ALL ON db1.* TO 'jeffrey'@'localhost';
GRANT SELECT ON db2.invoice TO 'jeffrey'@'localhost';
GRANT USAGE ON *.* TO 'jeffrey'@'localhost' WITH MAX_QUERIES_PER_HOUR 90;

However, if an account named in a GRANT statement does not already
exist, GRANT may create it under the conditions described later in the
discussion of the NO_AUTO_CREATE_USER SQL mode.

The REVOKE statement is related to GRANT and enables administrators to
remove account privileges. See [HELP REVOKE].

When successfully executed from the mysql program, GRANT responds with
Query OK, 0 rows affected. To determine what privileges result from the
operation, use SHOW GRANTS. See [HELP SHOW GRANTS].

URL: http://dev.mysql.com/doc/refman/5.5/en/grant.html

mysql> GRANT CREATE ON cactidb.* TO 'cactiuser'@'%';(授权cactiuser@%用户创建cactidb库、所有表、索引权限)
Query OK, 0 rows affected (0.00 sec)

测试:使用cactiuser@'%'用户创建cactidb数据库;

mysql> CREATE DATABASE cactidb;(创建数据库cactidb)
Query OK, 1 row affected (0.00 sec)

提示:可以创建cactidb数据库;

mysql> SHOW DATABASES;(显示数据库)
+--------------------+
| Database           |
+--------------------+
| information_schema |
| cactidb            |
| test               |
+--------------------+
3 rows in set (0.00 sec)

mysql> USE cactidb;(修改默认数据库为cactidb)
Database changed

mysql> CREATE TABLE testtb (ID INT UNSIGNED AUTO_INCREMENT NOT NULL, Name CHAR(20), PRIMARY KEY (ID));(创建表testtb,字段ID INT整型,UNSIGNED
无符号,AUTO_INCREMENT 自动增长,NOT NULL不允许为空,Name字段 CHAR(20)字符型,20字符,PRIMARY KEY(ID)定义ID字段为主键)
Query OK, 0 rows affected (0.03 sec)

mysql> INSERT INTO testtb (Name) VALUES ('Tom');(向testdb表中插入数据)
ERROR 1142 (42000): INSERT command denied to user 'cactiuser'@'localhost' for table 'testtb

提示:无法插入数据,只给cactidb@'%'用户创建库、表、索引权限,没有插入数据的权限;

mysql> GRANT INSERT ON cactidb.* TO 'cactiuser'@'%';(授权cactiuser@'%'用户对库cactidb所有表插入数据权限,用于表级别)
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;(刷新授权表)
Query OK, 0 rows affected (0.00 sec)

测试:通过cactiuser@'%'用户向cactidb库的testtb表插入数据

mysql> INSERT INTO testtb (Name) VALUES ('Tom');(向testtb表的Name字段插入数据)
ERROR 1142 (42000): INSERT command denied to user 'cactiuser'@'localhost' for table 'testtb'

提示:无法插入;

mysql> GRANT SELECT ON cactidb.* TO 'cactiuser'@'%';(授权cactiuser@'%'用户对库cactidb所有表有查询权限)
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;(刷新授权表)
Query OK, 0 rows affected (0.00 sec)

测试:通过cactiuser@'%'用户向cactidb库的testtb表插入数据

mysql> INSERT INTO testtb (Name) VALUES ('Tom');(向testtb表的Name字段插入数据)
ERROR 1142 (42000): INSERT command denied to user 'cactiuser'@'localhost' for table 'testtb'

提示:无法插入;

mysql> SHOW GRANTS FOR 'cactiuser'@'%';(查看cactiuser@'%'用户授权信息)
+----------------------------------------------------------------------------------------------------------+
| Grants for cactiuser@%                                                                                   |
+----------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'cactiuser'@'%' IDENTIFIED BY PASSWORD '*43DD7940383044FBDE5B177730FAD3405BC6DAD7' |
| GRANT SELECT, INSERT, CREATE ON `cactidb`.* TO 'cactiuser'@'%'                                           |
+----------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

提示:cactiuser@'%'用户有SELECT、INSERT、CREATE权限;

mysql> \q(退出)
Bye

[root@localhost ~]# tail /mydata/data/localhost.localdomain.err(查看localhost.localdomain.err日志文件后10行的内容)
160224 16:18:29 InnoDB: Completed initialization of buffer pool
160224 16:18:29 InnoDB: highest supported file format is Barracuda.
160224 16:18:29  InnoDB: Waiting for the background threads to start
160224 16:18:30 InnoDB: 1.1.8 started; log sequence number 1607585
160224 16:18:30 [Note] Server hostname (bind-address): '0.0.0.0'; port: 3306
160224 16:18:30 [Note]   - '0.0.0.0' resolves to '0.0.0.0';
160224 16:18:30 [Note] Server socket created on IP: '0.0.0.0'.
160224 16:18:30 [Note] Event Scheduler: Loaded 0 events
160224 16:18:30 [Note] /usr/local/mysql/bin/mysqld: ready for connections.
Version: '5.5.28-log'  socket: '/tmp/mysql.sock'  port: 3306  Source distribution

[root@localhost ~]# mysql -ucactiuser -p(通过ucactiuser用户连接mysql)
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 37
Server version: 5.5.28-log Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql> USE cactidb;(修改默认库为cactidb)
Database changed

mysql> INSERT INTO testtb (Name) VALUES ('Tom');(像testdb表插入数据)
Query OK, 1 row affected (0.00 sec)

提示:可以插入,它跟会话连接相关,它自己没有读授权表,可以让他自己FLUSH PRIVILEGES,但是它自己没有权限,所有只有重新连接以后才有权限;

mysql> FLUSH PRIVILEGES;(刷新授权表)
ERROR 1227 (42000): Access denied; you need (at least one of) the RELOAD privilege(s) for this operation

提示:没有权限;

mysql> SELECT * FROM testtb;(查看testtb表所有字段数据)
+----+------+
| ID | Name |
+----+------+
|  1 | Tom  |
+----+------+
1 row in set (0.00 sec)

提示:现在能查看所有字段,其实也可以授权用户仅能查看某些字段;

mysql> ALTER TABLE testtb ADD Age TINYINT UNSIGNED;(向testb表添加字段Age,TINYINT微整型,UNSIGNED无符号)
ERROR 1142 (42000): ALTER command denied to user 'cactiuser'@'localhost' for table 'testtb'

提示:没有权限使用ALTER命令;

mysql> GRANT ALTER ON cactidb.* TO 'cactiuser'@'%';(授权cactiuser@'%'用户对cactidb库所有表修改权限)
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;(刷新授权表)
Query OK, 0 rows affected (0.00 sec)

测试:通过cactiuser@'%'用户向cactidb的testtb表添加字段;

mysql> ALTER TABLE testtb ADD Age TINYINT UNSIGNED;(向testb表添加字段Age,TINYINT微整型,UNSIGNED无符号)
ERROR 1142 (42000): ALTER command denied to user 'cactiuser'@'localhost' for table 'testtb'
mysql> \q(退出)
Bye

[root@localhost ~]# mysql -ucactiuser -p(通过cactiuser用户连接mysql)
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 40
Server version: 5.5.28-log Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql> USE cactidb;(修改默认库为cactidb)           
Database changed

mysql> ALTER TABLE testtb ADD Age TINYINT UNSIGNED;(向testtb表添加字段Age,TINYINT微整型,UNSIGNED无符号)
Query OK, 1 row affected (0.05 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> DESC testtb;(查看testtb表结构)
+-------+---------------------+------+-----+---------+----------------+
| Field | Type                | Null | Key | Default | Extra          |
+-------+---------------------+------+-----+---------+----------------+
| ID    | int(10) unsigned    | NO   | PRI | NULL    | auto_increment |
| Name  | char(20)            | YES  |     | NULL    |                |
| Age   | tinyint(3) unsigned | YES  |     | NULL    |                |
+-------+---------------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> SELECT * FROM testtb;(查询testtb表所有字段数据)
+----+------+------+
| ID | Name | Age  |
+----+------+------+
|  1 | Tom  | NULL |
+----+------+------+
1 row in set (0.00 sec)

mysql> GRANT UPDATE(Age) ON cactidb.testtb TO 'cactiuser'@'%';(授权cactiuser@'%'用户更新cactidb库的testtb表的Age字段数据)
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;(刷新授权表)
Query OK, 0 rows affected (0.00 sec)

测试:通过cactiuser@'%'用户向cactidb库的testtb的Age字段修改数据;

[root@localhost ~]# mysql -ucactiuser -p(通过cactiuser用户连接mysql数据库)
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 42
Server version: 5.5.28-log Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql> USE cactidb;(修改默认库为cactidb)
Database changed

mysql> UPDATE testtb SET Age=30 WHERE ID=1; (更新testtb表的Age字段为30,条件ID等于1)
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SELECT * FROM testtb;(查询testtb表所有字段数据)
+----+------+------+
| ID | Name | Age  |
+----+------+------+
|  1 | Tom  |   30 |
+----+------+------+
1 row in set (0.00 sec)

mysql> UPDATE testtb SET Name='Jerry' WHERE ID=1;(更新testtb表的Name字段为Jerry,条件ID=1)
ERROR 1143 (42000): UPDATE command denied to user 'cactiuser'@'localhost' for column 'Name' in table 'testtb'

提示:无法修改,没有权限,授权只能修改Age一个字段,不能修改其它字段;

mysql> SHOW GRANTS FOR 'cactiuser'@'%';(查看cactiuser@'%'用户授权信息)
+----------------------------------------------------------------------------------------------------------+
| Grants for cactiuser@%                                                                                   |
+----------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'cactiuser'@'%' IDENTIFIED BY PASSWORD '*43DD7940383044FBDE5B177730FAD3405BC6DAD7' |
| GRANT SELECT, INSERT, CREATE, ALTER ON `cactidb`.* TO 'cactiuser'@'%'                                    |
| GRANT UPDATE (Age) ON `cactidb`.`testtb` TO 'cactiuser'@'%'                                              |
+----------------------------------------------------------------------------------------------------------+
3 rows in set (0.00 sec)

提示:在字段级别的权限是单独写的,其它权限都是合并起来了,只要在表级别存储过程、存储函数级别、或者是库级别的权限他们都合并在一起,而在字段或者列级别的权限都字段级别
合在一起分别进行存储;

mysql> SET GLOBAL tx_isolation='READ-UNCOMMITTED';(设置全局变量tx_isolation的值为读未提交)
ERROR 1227 (42000): Access denied; you need (at least one of) the SUPER privilege(s) for this operation

提示:没有SUPER权限;

mysql> GRANT SUPER ON *.* TO 'cactiuser'@'%';(授权cactiuser@'%'用户SUPER权限所有库所有表)
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;(刷新授权表)
Query OK, 0 rows affected (0.00 sec)

测试:通过cactiuser@'%'用户设置全局变量tx_isolation隔离级别为READ-UNCOMMITTED读未提交;

[root@localhost ~]# mysql -ucactiuser -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 47
Server version: 5.5.28-log Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql> SET GLOBAL tx_isolation='READ-UNCOMMITTED';(设置全局变量tx_isolation隔离级别为READ-UNCOMMITTED读未提交)
Query OK, 0 rows affected (0.00 sec)

提示:能不能把自己的权限授权给别人,比如创建一个用户把权限授权给它,没有GRANT OPTION, 只有自己再得到权限的时候使用了WITH GRANT OPTION才可以授权给别人的,一旦
我们自己在得到授权的时候别人给我们使用了WITH GRANT OPTION得到的结果是我们自己也可以授权给别人,而且还可以使用WITH GRANT OPTION, 也就意味着你可以逐级授权了,
所以说WITH GRANT OPTION是非常危险的,一般不建议使用;

mysql> HELP RENAME USER(查看重命名用户帮助)
Name: 'RENAME USER'
Description:
Syntax:
RENAME USER old_user TO new_user(old_user原来用户名,new_user新用户名)
    [, old_user TO new_user] ...

The RENAME USER statement renames existing MySQL accounts. To use it,
you must have the global CREATE USER privilege or the UPDATE privilege
for the mysql database. An error occurs if any old account does not
exist or any new account exists. Each account name uses the format
described in http://dev.mysql.com/doc/refman/5.5/en/account-names.html.
For example:

RENAME USER 'jeffrey'@'localhost' TO 'jeff'@'127.0.0.1';

If you specify only the user name part of the account name, a host name
part of '%' is used.

RENAME USER causes the privileges held by the old user to be those held
by the new user. However, RENAME USER does not automatically drop or
invalidate databases or objects within them that the old user created.
This includes stored programs or views for which the DEFINER attribute
names the old user. Attempts to access such objects may produce an
error if they execute in definer security context. (For information
about security context, see
http://dev.mysql.com/doc/refman/5.5/en/stored-programs-security.html.)

The privilege changes take effect as indicated in
http://dev.mysql.com/doc/refman/5.5/en/privilege-changes.html.

URL: http://dev.mysql.com/doc/refman/5.5/en/rename-user.html

mysql> HELP REVOKE(查看取消授权帮助)
Name: 'REVOKE'
Description:
Syntax:
REVOKE
    priv_type [(column_list)](priv_type权限类型,column_list字段级别)
      [, priv_type [(column_list)]] ...
    ON [object_type] priv_level(object_type对象类型包括表、函数、过程)
    FROM user [, user] ...

REVOKE ALL PRIVILEGES, GRANT OPTION
    FROM user [, user] ...

REVOKE PROXY ON user
    FROM user [, user] ...

The REVOKE statement enables system administrators to revoke privileges
from MySQL accounts. Each account name uses the format described in
http://dev.mysql.com/doc/refman/5.5/en/account-names.html. For example:

REVOKE INSERT ON *.* FROM 'jeffrey'@'localhost';

If you specify only the user name part of the account name, a host name
part of '%' is used.

For details on the levels at which privileges exist, the permissible
priv_type and priv_level values, and the syntax for specifying users
and passwords, see [HELP GRANT]

To use the first REVOKE syntax, you must have the GRANT OPTION
privilege, and you must have the privileges that you are revoking.

To revoke all privileges, use the second syntax, which drops all
global, database, table, column, and routine privileges for the named
user or users:

REVOKE ALL PRIVILEGES, GRANT OPTION FROM user [, user] ...

To use this REVOKE syntax, you must have the global CREATE USER
privilege or the UPDATE privilege for the mysql database.

URL: http://dev.mysql.com/doc/refman/5.5/en/revoke.html

mysql> SHOW GRANTS FOR 'cactiuser'@'%'; (查看cactiuser@'%'用户授权信息)
+----------------------------------------------------------------------------------------------------------+
| Grants for cactiuser@%                                                                                   |
+----------------------------------------------------------------------------------------------------------+
| GRANT SUPER ON *.* TO 'cactiuser'@'%' IDENTIFIED BY PASSWORD '*43DD7940383044FBDE5B177730FAD3405BC6DAD7' |
| GRANT SELECT, INSERT, CREATE, ALTER ON `cactidb`.* TO 'cactiuser'@'%'                                    |
| GRANT UPDATE (Age) ON `cactidb`.`testtb` TO 'cactiuser'@'%'                                              |
+----------------------------------------------------------------------------------------------------------+
3 rows in set (0.00 sec)

mysql> REVOKE SELECT ON cactidb.* FROM 'cactiuser'@'%';(取消cactiuser@'%'用户查询权限,在cactidb库所有表)
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW GRANTS FOR 'cactiuser'@'%';(查看cactiuser@'%'用户授权信息)
+----------------------------------------------------------------------------------------------------------+
| Grants for cactiuser@%                                                                                   |
+----------------------------------------------------------------------------------------------------------+
| GRANT SUPER ON *.* TO 'cactiuser'@'%' IDENTIFIED BY PASSWORD '*43DD7940383044FBDE5B177730FAD3405BC6DAD7' |
| GRANT INSERT, CREATE, ALTER ON `cactidb`.* TO 'cactiuser'@'%'                                            |
| GRANT UPDATE (Age) ON `cactidb`.`testtb` TO 'cactiuser'@'%'                                              |
+----------------------------------------------------------------------------------------------------------+
3 rows in set (0.00 sec)

提示:SELECT权限没有了,一般说来查询权限是读权限,这个我们都可以赋予的,只要允许它查数据,而其它权限大多数都是写权限,所以要慎重授权,尤其像SUPER、WITH GRANT 
OPTION这样的选项或权限;

如果MySQL管理员帐号忘记怎么办,如果我们里面没有任何有效数据,也没有有效其它用户的话,直接初始化MySQL库就可以了,把MySQL库删了重新初始化以下,但问题如果我们见了很
多其它用户,而且建了很多授权,也初始化就麻烦了,这时候怎么办,只能重新找回管理员密码,怎么找回,要想找回管理员密码,需要先关闭数据库服务,其次手动启动MySQL,使用命
令行启动也行,使用改脚步启动也行;

[root@localhost ~]# service mysqld stop(停止mysqld服务)
Shutting down MySQL...                                     [  OK  ]
[root@localhost ~]# vim /etc/init.d/mysqld(编辑mysqld服务脚步)

  'start')
    # Start daemon

    # Safeguard (relative paths, core dumps..)
    cd $basedir

    echo $echo_n "Starting MySQL"
    if test -x $bindir/mysqld_safe
    then
      # Give extra arguments to mysqld with the my.cnf file. This script
      # may be overwritten at next upgrade.
      $bindir/mysqld_safe --skip-grant-tables --skip-networking --datadir="$datadir" --pid-file="$mysqld_pid_file_path" $other_args >
/dev/null 2>&1 &(添加--skip-grant-tables跳过授权表,--skip-networking跳过网络,如果不跳过网络启动以后管理员没有密码,别人直接连接进来了,所以不允许别
人通过网络连接)
      wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$?

      # Make lock for RedHat / SuSE
      if test -w "$lockdir"
      then
        touch "$lock_file_path"
      fi

      exit $return_value
    else
      log_failure_msg "Couldn't find MySQL server ($bindir/mysqld_safe)"
    fi
    ;;

[root@localhost ~]# vim .my.cnf(编辑.my.cnf文件)

[client]
user = 'root'
password = 'redhat'
host = 'localhost'

[root@localhost ~]# service mysqld start(启动mysqld服务)
Starting MySQL..                                           [  OK  ]
[root@localhost ~]# rm .my.cnf(删除.my.cnf文件)
rm: remove regular file `.my.cnf'? y
[root@localhost ~]# mysql(连接mysql数据库)
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.5.28-log Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql> USE mysql;(更改默认数据库为mysql)
Database changed

mysql> SELECT User,Host,Password FROM user;(查询user表User、Host、Password字段数据)
+-----------+-----------------------+-------------------------------------------+
| User      | Host                  | Password                                  |
+-----------+-----------------------+-------------------------------------------+
| root      | localhost             | *84BB5DF4823DA319BBF86C99624479A198E6EEE9 |
| root      | localhost.localdomain | *84BB5DF4823DA319BBF86C99624479A198E6EEE9 |
| root      | 127.0.0.1             | *84BB5DF4823DA319BBF86C99624479A198E6EEE9 |
| cactiuser | %                     | *43DD7940383044FBDE5B177730FAD3405BC6DAD7 |
+-----------+-----------------------+-------------------------------------------+
4 rows in set (0.00 sec)

提示:这几个用户都有密码,这说明已经跳过去了;

mysql> SET PASSWORD FOR 'root'@'localhost'=PASSWORD('123456');(修改root@localhost用户密码为123456)   
ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement

提示:报错,提示MySQL服务器现在是跳过授权表的不能更改密码,所以使用--skip-grant-tables的时候使用SET PASSWORD FOR这种方式改密码就不可以了,只能手动更改user表
Password字段的数据;

mysql> UPDATE user SET PASSWORD=PASSWORD('123456') WHERE User='root';(更新user表设置密码为123456,使用PASSWORD函数加密存放,条件User等于root)
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0

mysql> SELECT User,Host,Password FROM user;(查询user表User、Host、Password字段数据)
+-----------+-----------------------+-------------------------------------------+
| User      | Host                  | Password                                  |
+-----------+-----------------------+-------------------------------------------+
| root      | localhost             | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |
| root      | localhost.localdomain | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |
| root      | 127.0.0.1             | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |
| cactiuser | %                     | *43DD7940383044FBDE5B177730FAD3405BC6DAD7 |
+-----------+-----------------------+-------------------------------------------+
4 rows in set (0.00 sec)

提示:三个密码都改了。

mysql> \q(退出)
Bye

[root@localhost ~]# service mysqld stop(停止MySQL服务)
Shutting down MySQL.                                       [  OK  ]

[root@localhost ~]# vim /etc/init.d/mysqld 

  'start')
    # Start daemon

    # Safeguard (relative paths, core dumps..)
    cd $basedir

    echo $echo_n "Starting MySQL"
    if test -x $bindir/mysqld_safe
    then
      # Give extra arguments to mysqld with the my.cnf file. This script
      # may be overwritten at next upgrade.
      $bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" $other_args >/dev/null 2>&1 &(去掉选项--skip-grant-tables
和--skip-networking)
      wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$?

      # Make lock for RedHat / SuSE
      if test -w "$lockdir"
      then
        touch "$lock_file_path"
      fi

      exit $return_value
    else
      log_failure_msg "Couldn't find MySQL server ($bindir/mysqld_safe)"
    fi
    ;;

[root@localhost ~]# service mysqld start(启动mysqld服务)
Starting MySQL                                             [  OK  ]
[root@localhost ~]# mysql(连接mysql)
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
提示:不输入密码连接不上去了;
[root@localhost ~]# mysql -uroot -p(通过root用户连接mysql)
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.5.28-log Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql> \q(退出)
Bye

Logs, Backups and Recovery

错误日志: 错误日志不仅仅记录错误日志信息,它还可以记录其它类别的信息;

  log_error(错误日志开关)

  log_warnings(警告日志开关)

一般查询日志: 一般不启用一般查询日志,每执行一个SELECT语句,一个DML语句它都有可能涉及到一系列的查询操作,对于非常繁忙的服务器如果每次查询都要记录下来可能会产生大量日志信息;

  general_log(一般查询开关)

  general_file(一般查询日志文件目录)

  log

  log_outpu(一般查询存储方式有FILE、TABLE、NONE)

慢查询日志: 执行了很长时间的查询操作,通常为了定位服务器查询性能问题都应该启用慢查询日志,当问题是执行了多长时间的查询属于慢查询,一般来来讲一个查询能够执行1S钟就相当长的时间了,可以使用变量来定义;

  long_query_time                10.000000(慢查询定义时间)

  log_slow_queries={YES|NO} (是否记录慢查询)

  slow_query_log(慢查日志开关)

  slow_query_log_file                /mydata/data/localhost-slow.log(慢查询日志文件存放位置)

二进制日志: 任何引起或可能引起数据库变化的操作,记录格式是二进制,而且是MySQL独有的二进制格式,能够快速记录日志锁产生的信息,它只记录DML语句和DDL语句所产生的信息,也包括DCL,任何能够引起数据库改变或者潜在有可能引起数据库改变的语句信息执行的操作都会记录下来,非常重要的日志,用于实现MySQL复制以及MySQL即时点恢复的重要依据;

  复制、即时点恢复;

  mysqlbinlog 查看二进制日志命令

  二进制日志的格式:

    基于语句:statement 如果两次重放的操作结果是一样的就记录语句,因为语句简单的多;

    基于行:row 这个引起了改变,就把这行记录下来,

    混合方式: mixed

  二进制日志事件:

    产生的时间

    相对位置

  二进制日志文件:

    索引文件

    二进制日志文件

  查看当前正在使用的二进制日志文件

  mysql> SHOW MASTER STATUS;

  mysql> SHOW BINARY LOGS;(查看mysql仍然拥有的二进制日志文件)

  mysql> SHOW BINLOG EVENTS IN '二进制日志文件名' [FROM pos] (查看二进制日志文件内容,pos日志文件开始时间点)

  mysql> PURGE BINARY LOGS TO '某个二进制日志文件'(删除某二进制文件之前的日志文件,当前指定的不会删除)

  mysqlbinlog 查看二进制日志命令

    --start-datetime 开始时间

    --stop-datetime 结束时间

    --start-position 开始时间的位置

    --stop-position 结束时间的位置

position 位置

startime 起始时间

中继日志:中继日志格式和二进制一样,因为它是复制的二进制日志,只不过它的作用和功能并不完全一样,因为中继日志仅仅是在当前从服务器上要求要执行一遍的日志文件,但它格式相同;

事务日志:在事务存储引擎有的日志文件,为了保证给事务提供所谓的原子性、一致性重要的组建,它能保证将随机I/O转换为顺序I/O从而提高性能,并且能够保证事务提交以后不会丢失,只有事务性存储引擎才需要用到事务日志,比如InooDB就有事务日志;

MySQL复制功能就是我们的从服务器不停的从主服务器上把它二进制日志里面的所产生的任何操作,它把所有的操作通过MySQL客户端和服务器端协议读取过来一份并保存到本地的某个日志文件里面,而后由MySQL本地的某一个服务器线程每一次从这个日志文件中读取一行并在本地数据库上操作一次,执行一次一模一样的操作,假如主服务器删除一行,这个删除的操作会记录到日志文件里面,而后我们的从服务器就把这个操作复制过来,从二进制日志中复制过来并保存到本地日志当中,而后MySQL本地从服务器本地的线程称为SQL线程和I/O线程,有其中某一个线程将这个日志事件读取出来并在本地执行一次,比如删除一行,于是这个操作在本地它也读过来删除本地数据库上的一行,所以两个数据库服务器就一样了,这就是复制,所以二进制日志是保证复制功能重要的依据,而更重要的是从服务器需要把日志复制过来一份保存到本地的文件当中,对于从服务器来讲它也需要一个日志文件,而这个日志文件称为中继日志,

Error log(错误日志)

Contains entries for when the mysqld daemon started and stopped and also any critical errors that occur while the server is running

Information such as when the event scheduler executes an event and when replication starts and stops is also written to the error log

服务器启动和关闭过程中的信息

服务器运行过程中的错误信息

事件调度器运行一个事件时产生的信息

在从服务器上启动从服务器进程时产生的信息

MySQL在启动的时候默认没有启动任何日志功能,MySQL进程自身没有,它只不过借助配置文件启动了错误日志的功能,

TO enable the error log, specify the log-error option

  The error log will be written to the data directory using the format host_name.err

  To customize the filename, give the log-error option a filename,such as:

    log-error=/var/log/mysqld.err

The log_warnings option is used to control whether or not warning messages are logged to the error log(log_warning记录警告信息,是不是把警告信息也记录日志)

  The default value is 1 (enabled)

  If the value is greater than 1, aborted connections are written to the error log

If you do not specify log-error, or if you use the -- console option on Windoes, errors are written to stderr, the standard error output

expire_logs_days={0..99}

设定二进制日志的过期天数,超出此天数的二进制日志文件将被自动删除。默认为0,表示不启用过期自动删除功能。如果启用此功能,自动删除工作通常发生在MySQL启动时或FLUSH日志时。作用范围为全局,可用于配置文件,属动态变量。

general_log={ON|OFF}

设定是否启用查询日志,默认值为取决于在启动mysqld时是否使用了--general_log选项。如若启用此项,其输出位置则由--log_output选项进行定义,如果log_output的值设定为NONE,即使用启用查询日志,其也不会记录任何日志信息。作用范围为全局,可用于配置文件,属动态变量。

general_log_file=FILE_NAME

查询日志的日志文件名称,默认为“hostname.log"。作用范围为全局,可用于配置文件,属动态变量。


binlog-format={ROW|STATEMENT|MIXED}

指定二进制日志的类型,默认为STATEMENT。如果设定了二进制日志的格式,却没有启用二进制日志,则MySQL启动时会产生警告日志信息并记录于错误日志中。作用范围为全局或会话,可用于配置文件,且属于动态变量。

log={YES|NO}

是否启用记录所有语句的日志信息于一般查询日志(general query log)中,默认通常为OFF。MySQL 5.6已经弃用此选项。

log-bin={YES|NO}

是否启用二进制日志,如果为mysqld设定了--log-bin选项,则其值为ON,否则则为OFF。其仅用于显示是否启用了二进制日志,并不反应log-bin的设定值。作用范围为全局级别,属非动态变量。

log_bin_trust_function_creators={TRUE|FALSE}

此参数仅在启用二进制日志时有效,用于控制创建存储函数时如果会导致不安全的事件记录二进制日志条件下是否禁止创建存储函数。默认值为0,表示除非用户除了CREATE ROUTING或ALTER ROUTINE权限外还有SUPER权限,否则将禁止创建或修改存储函数,同时,还要求在创建函数时必需为之使用DETERMINISTIC属性,再不然就是附带READS SQL DATA或NO SQL属性。设置其值为1时则不启用这些限制。作用范围为全局级别,可用于配置文件,属动态变量。

log_error=/PATH/TO/ERROR_LOG_FILENAME

定义错误日志文件。作用范围为全局或会话级别,可用于配置文件,属非动态变量。

log_output={TABLE|FILE|NONE}

定义一般查询日志和慢查询日志的保存方式,可以是TABLE、FILE、NONE,也可以是TABLE及FILE的组合(用逗号隔开),默认为TABLE。如果组合中出现了NONE,那么其它设定都将失效,同时,无论是否启用日志功能,也不会记录任何相关的日志信息。作用范围为全局级别,可用于配置文件,属动态变量。

log_query_not_using_indexes={ON|OFF}

设定是否将没有使用索引的查询操作记录到慢查询日志。作用范围为全局级别,可用于配置文件,属动态变量。

log_slave_updates

用于设定复制场景中的从服务器是否将从主服务器收到的更新操作记录进本机的二进制日志中。本参数设定的生效需要在从服务器上启用二进制日志功能。

log_slow_queries={YES|NO}

是否记录慢查询日志。慢查询是指查询的执行时间超出long_query_time参数所设定时长的事件。MySQL 5.6将此参数修改为了slow_query_log。作用范围为全局级别,可用于配置文件,属动态变量。

log_warnings=#

设定是否将警告信息记录进错误日志。默认设定为1,表示启用;可以将其设置为0以禁用;而其值为大于1的数值时表示将新发起连接时产生的“失败的连接”和“拒绝访问”类的错误信息也记录进错误日志。

long_query_time=#

设定区别慢查询与一般查询的语句执行时间长度。这里的语句执行时长为实际的执行时间,而非在CPU上的执行时长,因此,负载较重的服务器上更容易产生慢查询。其最小值为0,默认值为10,单位是秒钟。它也支持毫秒级的解析度。作用范围为全局或会话级别,可用于配置文件,属动态变量。

max_binlog_cache_size{4096 .. 18446744073709547520}

二进定日志缓存空间大小,5.5.9及以后的版本仅应用于事务缓存,其上限由max_binlog_stmt_cache_size决定。作用范围为全局级别,可用于配置文件,属动态变量。

max_binlog_size={4096 .. 1073741824}

设定二进制日志文件上限,单位为字节,最小值为4K,最大值为1G,默认为1G。某事务所产生的日志信息只能写入一个二进制日志文件,因此,实际上的二进制日志文件可能大于这个指定的上限。作用范围为全局级别,可用于配置文件,属动态变量。

 


max_relay_log_size={4096..1073741824}

设定从服务器上中继日志的体积上限,到达此限度时其会自动进行中继日志滚动。此参数值为0时,mysqld将使用max_binlog_size参数同时为二进制日志和中继日志设定日志文件体积上限。作用范围为全局级别,可用于配置文件,属动态变量。

innodb_log_buffer_size={262144 .. 4294967295}

设定InnoDB用于辅助完成日志文件写操作的日志缓冲区大小,单位是字节,默认为8MB。较大的事务可以借助于更大的日志缓冲区来避免在事务完成之前将日志缓冲区的数据写入日志文件,以减少I/O操作进而提升系统性能。因此,在有着较大事务的应用场景中,建议为此变量设定一个更大的值。作用范围为全局级别,可用于选项文件,属非动态变量。

innodb_log_file_size={108576 .. 4294967295}

设定日志组中每个日志文件的大小,单位是字节,默认值是5MB。较为明智的取值范围是从1MB到缓存池体积的1/n,其中n表示日志组中日志文件的个数。日志文件越大,在缓存池中需要执行的检查点刷写操作就越少,这意味着所需的I/O操作也就越少,然而这也会导致较慢的故障恢复速度。作用范围为全局级别,可用于选项文件,属非动态变量。

innodb_log_files_in_group={2 .. 100}

设定日志组中日志文件的个数。InnoDB以循环的方式使用这些日志文件。默认值为2。作用范围为全局级别,可用于选项文件,属非动态变量。

innodb_log_group_home_dir=/PATH/TO/DIR

设定InnoDB重做日志文件的存储目录。在缺省使用InnoDB日志相关的所有变量时,其默认会在数据目录中创建两个大小为5MB的名为ib_logfile0和ib_logfile1的日志文件。作用范围为全局级别,可用于选项文件,属非动态变量。


relay_log=file_name

设定中继日志的文件名称,默认为host_name-relay-bin。也可以使用绝对路径,以指定非数据目录来存储中继日志。作用范围为全局级别,可用于选项文件,属非动态变量。

relay_log_index=file_name

设定中继日志的索引文件名,默认为为数据目录中的host_name-relay-bin.index。作用范围为全局级别,可用于选项文件,属非动态变量。

relay-log-info-file=file_name

设定中继服务用于记录中继信息的文件,默认为数据目录中的relay-log.info。作用范围为全局级别,可用于选项文件,属非动态变量。


relay_log_purge={ON|OFF}

设定对不再需要的中继日志是否自动进行清理。默认值为ON。作用范围为全局级别,可用于选项文件,属动态变量。

relay_log_space_limit=#

设定用于存储所有中继日志文件的可用空间大小。默认为0,表示不限定。最大值取决于系统平台位数。作用范围为全局级别,可用于选项文件,属非动态变量。


slow_query_log={ON|OFF}

设定是否启用慢查询日志。0或OFF表示禁用,1或ON表示启用。日志信息的输出位置取决于log_output变量的定义,如果其值为NONE,则即便slow_query_log为ON,也不会记录任何慢查询信息。作用范围为全局级别,可用于选项文件,属动态变量。

slow_query_log_file=/PATH/TO/SOMEFILE

设定慢查询日志文件的名称。默认为hostname-slow.log,但可以通过--slow_query_log_file选项修改。作用范围为全局级别,可用于选项文件,属动态变量。


sql_log_bin={ON|OFF}

用于控制二进制日志信息是否记录进日志文件。默认为ON,表示启用记录功能。用户可以在会话级别修改此变量的值,但其必须具有SUPER权限。作用范围为全局和会话级别,属动态变量。

sql_log_off={ON|OFF}

用于控制是否禁止将一般查询日志类信息记录进查询日志文件。默认为OFF,表示不禁止记录功能。用户可以在会话级别修改此变量的值,但其必须具有SUPER权限。作用范围为全局和会话级别,属动态变量。

sync_binlog=#

设定多久同步一次二进制日志至磁盘文件中,0表示不同步,任何正数值都表示对二进制每多少次写操作之后同步一次。当autocommit的值为1时,每条语句的执行都会引起二进制日志同步,否则,每个事务的提交会引起二进制日志同步。

[root@localhost ~]# mysql(连接mysql数据库)
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.5.28-log Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql> SHOW GLOBAL VARIABLES LIKE '%log%';(查看全局变量中间为log的变量)
+-----------------------------------------+----------------------------------------+
| Variable_name                           | Value                                  |
+-----------------------------------------+----------------------------------------+
| back_log                                | 50                                     |
| binlog_cache_size                       | 32768                                  |(二进制日志)
| binlog_direct_non_transactional_updates | OFF                                    |
| binlog_format                           | MIXED                                  |
| binlog_stmt_cache_size                  | 32768                                  |
| expire_logs_days                        | 0                                      |
| general_log                             | OFF                                    |(一般查询日志,是否启用一般查询日志,默认都是关闭)
| general_log_file                        | /mydata/data/localhost.log             |(一般查询日志文件记录的目录)
| innodb_flush_log_at_trx_commit          | 1                                      |(innodb事务日志)
| innodb_locks_unsafe_for_binlog          | OFF                                    |
| innodb_log_buffer_size                  | 8388608                                |
| innodb_log_file_size                    | 5242880                                |
| innodb_log_files_in_group               | 2                                      |
| innodb_log_group_home_dir               | ./                                     |
| innodb_mirrored_log_groups              | 1                                      |
| log                                     | OFF                                    |(一般查询日志)
| log_bin                                 | ON                                     |(日志输出格式)
| log_bin_trust_function_creators         | OFF                                    |
| log_error                               | /mydata/data/localhost.localdomain.err |(错误日志信息,默认在数据目录下,当前主机名加.err的文件)
| log_output                              | FILE                                   |(一般查询日志信息输出到那里,默认是文件,还可以记录到表中)
| log_queries_not_using_indexes           | OFF                                    |
| log_slave_updates                       | OFF                                    |
| log_slow_queries                        | OFF                                    |(慢查询日志)
| log_warnings                            | 1                                      |(错误日志,警告信息)
| max_binlog_cache_size                   | 18446744073709547520                   |(binlog文件大小格式的)
| max_binlog_size                         | 1073741824                             |
| max_binlog_stmt_cache_size              | 18446744073709547520                   |
| max_relay_log_size                      | 0                                      |
| relay_log                               |                                        |(中继日志)
| relay_log_index                         |                                        |
| relay_log_info_file                     | relay-log.info                         |
| relay_log_purge                         | ON                                     |
| relay_log_recovery                      | OFF                                    |
| relay_log_space_limit                   | 0                                      |
| slow_query_log                          | OFF                                    |(慢查日志开关)
| slow_query_log_file                     | /mydata/data/localhost-slow.log        |(慢查询日志文件存放位置)
| sql_log_bin                             | ON                                     |(手动定义是否启用关闭二进制日志)
| sql_log_off                             | OFF                                    |
| sync_binlog                             | 0                                      |(是不是将日志从缓存同步到磁盘文件,为了加速一般不会理解写到磁盘,
而是记录到内存中的缓存中)
| sync_relay_log                          | 0                                      |
| sync_relay_log_info                     | 0                                      |
+-----------------------------------------+----------------------------------------+
41 rows in set (0.00 sec)

提示:MySQL靠各种服务器变量或者服务器启动时候的参数来定义各类日志启用与否,以及如果启用的话日志文件是什么,还有包括像InnoDB日志,事务日志有个日志组,里面有两个轮替着
使用,这些日志文件都是什么;

mysql> SHOW GLOBAL VARIABLES LIKE '%long%';(查看mysql全局变量中间为long的变量值)
+---------------------------------------------------+-----------+
| Variable_name                                     | Value     |
+---------------------------------------------------+-----------+
| long_query_time                                   | 10.000000 |(慢查询时间)
| max_long_data_size                                | 1048576   |
| performance_schema_events_waits_history_long_size | 10000     |
+---------------------------------------------------+-----------+
3 rows in set (0.00 sec)

mysql> SET GLOBAL slow_query_log=1;(设置全局变量慢查询日志开启)
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW GLOBAL VARIABLES LIKE '%log%';(查看全局变量中间为log的变量)
+-----------------------------------------+----------------------------------------+
| Variable_name                           | Value                                  |
+-----------------------------------------+----------------------------------------+
| back_log                                | 50                                     |
| binlog_cache_size                       | 32768                                  |(二进制日志)
| binlog_direct_non_transactional_updates | OFF                                    |
| binlog_format                           | MIXED                                  |
| binlog_stmt_cache_size                  | 32768                                  |
| expire_logs_days                        | 0                                      |
| general_log                             | OFF                                    |(一般查询日志,是否启用一般查询日志,默认都是关闭)
| general_log_file                        | /mydata/data/localhost.log             |(一般查询日志文件记录的目录)
| innodb_flush_log_at_trx_commit          | 1                                      |(innodb事务日志)
| innodb_locks_unsafe_for_binlog          | OFF                                    |
| innodb_log_buffer_size                  | 8388608                                |
| innodb_log_file_size                    | 5242880                                |
| innodb_log_files_in_group               | 2                                      |
| innodb_log_group_home_dir               | ./                                     |
| innodb_mirrored_log_groups              | 1                                      |
| log                                     | OFF                                    |(一般查询日志)
| log_bin                                 | ON                                     |(日志输出格式)
| log_bin_trust_function_creators         | OFF                                    |
| log_error                               | /mydata/data/localhost.localdomain.err |(错误日志信息,默认在数据目录下,当前主机名加.err的文件)
| log_output                              | FILE                                   |(一般查询日志信息输出到那里,默认是文件,还可以记录到表中)
| log_queries_not_using_indexes           | OFF                                    |
| log_slave_updates                       | OFF                                    |
| log_slow_queries                        | ON                                     |(慢查询日志)
| log_warnings                            | 1                                      |(错误日志,警告信息)
| max_binlog_cache_size                   | 18446744073709547520                   |(binlog文件大小格式的)
| max_binlog_size                         | 1073741824                             |
| max_binlog_stmt_cache_size              | 18446744073709547520                   |
| max_relay_log_size                      | 0                                      |
| relay_log                               |                                        |(中继日志)
| relay_log_index                         |                                        |
| relay_log_info_file                     | relay-log.info                         |
| relay_log_purge                         | ON                                     |
| relay_log_recovery                      | OFF                                    |
| relay_log_space_limit                   | 0                                      |
| slow_query_log                          | ON                                     |(慢查日志开关)
| slow_query_log_file                     | /mydata/data/localhost-slow.log        |(慢查询日志文件存放位置)
| sql_log_bin                             | ON                                     |(手动定义是否启用关闭二进制日志)
| sql_log_off                             | OFF                                    |
| sync_binlog                             | 0                                      |(是不是将日志从缓存同步到磁盘文件,为了加速一般不会理解写到磁盘,
而是记录到内存中的缓存中)
| sync_relay_log                          | 0                                      |
| sync_relay_log_info                     | 0                                      |
+-----------------------------------------+----------------------------------------+
41 rows in set (0.00 sec)

提示:slow_query_log状态为ON,log_slow_queries状态也自动为ON,这样就可以记录慢查询日志了;

mysql> \q(退出)
Bye

[root@localhost data]# ls(查看当前目录文件及子目录)
cactidb  ibdata1      jiaowu                     localhost-slow.log  mysql-bin.000001  mysql-bin.000004  performance_schema  testdb
edb      ib_logfile0  localhost.localdomain.err  mydb                mysql-bin.000002  mysql-bin.000005  students
hellodb  ib_logfile1  localhost.localdomain.pid  mysql               mysql-bin.000003  mysql-bin.index   test
[root@localhost data]# cat mysql-bin.index(查看mysql-bin.index文件内容)
./mysql-bin.000001
./mysql-bin.000002
./mysql-bin.000003
./mysql-bin.000004
./mysql-bin.000005
提示:一共产生5个日志文件,索引文件里面记录了我们每一个还仍然能被服务器找着的日志文件,它有指针,明确说明开始文件是谁,结束文件是谁,结束的一般是当前正在使用的;
[root@localhost data]# mysql(连接mysql)
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 7
Server version: 5.5.28-log Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql> SHOW MASTER STATUS;(查看正在使用的二进制日志文件)
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000005 |      107 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.04 sec)

提示:Position上一个时间结束的位置,如果此时往数据库中插入了新的内容,比如执行DML语句任何能够引起数据库改变的内容,这个位置会改变,这个位置指的是上次事件结束的位置;

mysql> USE jiaowu;(改变默认数据库为jiaowu)
Database changed
mysql> SHOW TABLES;(显示表)
+------------------+
| Tables_in_jiaowu |
+------------------+
| courses          |
| scores           |
| sct              |
| students         |
| tutors           |
+------------------+
5 rows in set (0.00 sec)

注意:显示表不会让Position时间结束位置改变的,只记录那些引起数据库改变的操作;

mysql> SHOW MASTER STATUS;(查看正在使用二进制日志文件)
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000005 |      107 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

mysql> INSERT INTO tutors (Tname,Gender,Age) VALUE ('stu100','M',30);(向tutors表的Tname、Gender、Age字段插入数据)
Query OK, 1 row affected (0.00 sec)

mysql> SHOW MASTER STATUS;(查看正在使用二进制日志文件)
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000005 |      358 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

提示:Position时间结束位置发生改变,刚才所操作的内容是358-107的偏移就是刚才事件记录的空间;

mysql> SHOW BINLOG EVENTS IN 'mysql-bin.000005';(查看二进制日志文件mysql-bin.000005内容)
+------------------+-----+-------------+-----------+-------------+-----------------------------------------------------------------------------+
| Log_name         | Pos | Event_type  | Server_id | End_log_pos | Info                                                                        |
+------------------+-----+-------------+-----------+-------------+-----------------------------------------------------------------------------+
| mysql-bin.000005 |   4 | Format_desc |         1 |         107 | Server ver: 5.5.28-log, Binlog ver: 4                                       |
| mysql-bin.000005 | 107 | Query       |         1 |         177 | BEGIN                                                                       |
| mysql-bin.000005 | 177 | Intvar      |         1 |         205 | INSERT_ID=13                                                                |
| mysql-bin.000005 | 205 | Query       |         1 |         331 | use `jiaowu`; INSERT INTO tutors (Tname,Gender,Age) VALUE ('stu100','M',30) |
| mysql-bin.000005 | 331 | Xid         |         1 |         358 | COMMIT /* xid=19 */                                                         |
+------------------+-----+-------------+-----------+-------------+-----------------------------------------------------------------------------+
5 rows in set (0.00 sec)

提示:文件头,Server ver: 5.5.28-log, Binlog ver: 4日志头,服务器版本号,日志文件版本号,二进制日志文件版本号;

mysql> SHOW BINLOG EVENTS IN 'mysql-bin.000005' FROM 107;(查看二进制日志文件mysql-bin.000005内容,从107时间点开始显示)
+------------------+-----+------------+-----------+-------------+-----------------------------------------------------------------------------+
| Log_name         | Pos | Event_type | Server_id | End_log_pos | Info                                                                        |
+------------------+-----+------------+-----------+-------------+-----------------------------------------------------------------------------+
| mysql-bin.000005 | 107 | Query      |         1 |         177 | BEGIN                                                                       |
| mysql-bin.000005 | 177 | Intvar     |         1 |         205 | INSERT_ID=13                                                                |
| mysql-bin.000005 | 205 | Query      |         1 |         331 | use `jiaowu`; INSERT INTO tutors (Tname,Gender,Age) VALUE ('stu100','M',30) |
| mysql-bin.000005 | 331 | Xid        |         1 |         358 | COMMIT /* xid=19 */                                                         |
+------------------+-----+------------+-----------+-------------+-----------------------------------------------------------------------------+
4 rows in set (0.00 sec)

提示:Server_id由那个服务器所产生的二进制日志,Event_type时间类型,

mysql> \q(退出)
Bye

[root@localhost data]# ls(查看当前目录文件及子目录)
cactidb  ibdata1      jiaowu                     localhost-slow.log  mysql-bin.000001  mysql-bin.000004  performance_schema  testdb
edb      ib_logfile0  localhost.localdomain.err  mydb                mysql-bin.000002  mysql-bin.000005  students
hellodb  ib_logfile1  localhost.localdomain.pid  mysql               mysql-bin.000003  mysql-bin.index   test
[root@localhost data]# man mysqlbinlog(查看mysqlbinlog命令man帮助)

       ·   --start-datetime=datetime

           Start reading the binary log at the first event having a timestamp equal to or later than the datetime argument. The
           datetime value is relative to the local time zone on the machine where you run mysqlbinlog. The value should be in a format
           accepted for the DATETIME or TIMESTAMP data types. For example:

               shell> mysqlbinlog --start-datetime="2005-12-25 11:25:56" binlog.000003

           This option is useful for point-in-time recovery. See Section 7.3, "Example Backup and Recovery Strategy".

       ·   --stop-datetime=datetime

           Stop reading the binary log at the first event having a timestamp equal to or later than the datetime argument. This option
           is useful for point-in-time recovery. See the description of the --start-datetime option for information about the datetime
           value.

           This option is useful for point-in-time recovery. See Section 7.3, "Example Backup and Recovery Strategy".

[root@localhost data]# mysqlbinlog mysql-bin.000005(查看mysql二进制日志文件mysql-bin.000005文件年日哦那个) 
/*!40019 SET @@session.max_insert_delayed_threads=0*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;(文件头部)
# at 4(第4个位置)
#160227  6:01:39(产生时间) server id 1(那个服务器产生)  end_log_pos 107(结束位置) 	Start: binlog v 4, server v 5.5.28-log 
created 160227  6:01:39 at startup(文件头部)
# Warning: this binlog is either in use or was not closed properly.
ROLLBACK/*!*/;
BINLOG '
Q8vQVg8BAAAAZwAAAGsAAAABAAQANS41LjI4LWxvZwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAABDy9BWEzgNAAgAEgAEBAQEEgAAVAAEGggAAAAICAgCAA==
'/*!*/;
# at 107
#160227(事件产生时间) 11:27:05 server id 1(那个服务器产生)  end_log_pos 177(结束位置) 	Query(类型)	thread_id=7(线程号)	
exec_time=0(执行时长)	error_code=0(错误代码)
SET TIMESTAMP=1456543625/*!*/;
SET @@session.pseudo_thread_id=7/*!*/;
SET @@session.foreign_key_checks=1, @@session.sql_auto_is_null=0, @@session.unique_checks=1, @@session.autocommit=1/*!*/;
SET @@session.sql_mode=0/*!*/;
SET @@session.auto_increment_increment=1, @@session.auto_increment_offset=1/*!*/;
/*!\C latin1 *//*!*/;
SET @@session.character_set_client=8,@@session.collation_connection=8,@@session.collation_server=8/*!*/;
SET @@session.lc_time_names=0/*!*/;
SET @@session.collation_database=DEFAULT/*!*/;
BEGIN
/*!*/;
# at 177
#160227 11:27:05 server id 1  end_log_pos 205 	Intvar
SET INSERT_ID=13/*!*/;
# at 205
#160227 11:27:05 server id 1  end_log_pos 331 	Query	thread_id=7	exec_time=0	error_code=0
use jiaowu/*!*/;
SET TIMESTAMP=1456543625/*!*/;
INSERT INTO tutors (Tname,Gender,Age) VALUE ('stu100','M',30)
/*!*/;
# at 331
#160227 11:27:05 server id 1  end_log_pos 358 	Xid = 19
COMMIT/*!*/;
DELIMITER ;
# End of log file
ROLLBACK /* added by mysqlbinlog */;
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;

[root@localhost data]# mysqlbinlog --start-position=107 --stop-position=358 mysql-bin.000005(查看mysql二进制日志文件mysql-bin.000005内容,
--start-position开始时间位置,--stop-position结束时间位置) 
/*!40019 SET @@session.max_insert_delayed_threads=0*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 4
#160227  6:01:39 server id 1  end_log_pos 107 	Start: binlog v 4, server v 5.5.28-log created 160227  6:01:39 at startup
# Warning: this binlog is either in use or was not closed properly.
ROLLBACK/*!*/;
BINLOG '
Q8vQVg8BAAAAZwAAAGsAAAABAAQANS41LjI4LWxvZwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAABDy9BWEzgNAAgAEgAEBAQEEgAAVAAEGggAAAAICAgCAA==
'/*!*/;
# at 107
#160227 11:27:05 server id 1  end_log_pos 177 	Query	thread_id=7	exec_time=0	error_code=0
SET TIMESTAMP=1456543625/*!*/;
SET @@session.pseudo_thread_id=7/*!*/;
SET @@session.foreign_key_checks=1, @@session.sql_auto_is_null=0, @@session.unique_checks=1, @@session.autocommit=1/*!*/;
SET @@session.sql_mode=0/*!*/;
SET @@session.auto_increment_increment=1, @@session.auto_increment_offset=1/*!*/;
/*!\C latin1 *//*!*/;
SET @@session.character_set_client=8,@@session.collation_connection=8,@@session.collation_server=8/*!*/;
SET @@session.lc_time_names=0/*!*/;
SET @@session.collation_database=DEFAULT/*!*/;
BEGIN
/*!*/;
# at 177
#160227 11:27:05 server id 1  end_log_pos 205 	Intvar
SET INSERT_ID=13/*!*/;
# at 205
#160227 11:27:05 server id 1  end_log_pos 331 	Query	thread_id=7	exec_time=0	error_code=0
use jiaowu/*!*/;
SET TIMESTAMP=1456543625/*!*/;
INSERT INTO tutors (Tname,Gender,Age) VALUE ('stu100','M',30)
/*!*/;
# at 331
#160227 11:27:05 server id 1  end_log_pos 358 	Xid = 19
COMMIT/*!*/;
DELIMITER ;
# End of log file
ROLLBACK /* added by mysqlbinlog */;
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;

[root@localhost data]# mysqlbinlog --start-position=177 --stop-position=358 mysql-bin.000005(查看mysql二进制日志文件mysql-bin.000005内容,
--start-position开始时间位置,--stop-position结束时间位置) 
 
/*!40019 SET @@session.max_insert_delayed_threads=0*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 4
#160227  6:01:39 server id 1  end_log_pos 107 	Start: binlog v 4, server v 5.5.28-log created 160227  6:01:39 at startup
# Warning: this binlog is either in use or was not closed properly.
ROLLBACK/*!*/;
BINLOG '
Q8vQVg8BAAAAZwAAAGsAAAABAAQANS41LjI4LWxvZwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAABDy9BWEzgNAAgAEgAEBAQEEgAAVAAEGggAAAAICAgCAA==
'/*!*/;(文件头一定会显示)
# at 177
#160227 11:27:05 server id 1  end_log_pos 205 	Intvar
SET INSERT_ID=13/*!*/;
# at 205
#160227 11:27:05 server id 1  end_log_pos 331 	Query	thread_id=7	exec_time=0	error_code=0
use jiaowu/*!*/;
SET TIMESTAMP=1456543625/*!*/;
SET @@session.pseudo_thread_id=7/*!*/;
SET @@session.foreign_key_checks=1, @@session.sql_auto_is_null=0, @@session.unique_checks=1, @@session.autocommit=1/*!*/;
SET @@session.sql_mode=0/*!*/;
SET @@session.auto_increment_increment=1, @@session.auto_increment_offset=1/*!*/;
/*!\C latin1 *//*!*/;
SET @@session.character_set_client=8,@@session.collation_connection=8,@@session.collation_server=8/*!*/;
SET @@session.lc_time_names=0/*!*/;
SET @@session.collation_database=DEFAULT/*!*/;
INSERT INTO tutors (Tname,Gender,Age) VALUE ('stu100','M',30)
/*!*/;
# at 331
#160227 11:27:05 server id 1  end_log_pos 358 	Xid = 19
COMMIT/*!*/;
DELIMITER ;
# End of log file
ROLLBACK /* added by mysqlbinlog */;
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
[root@localhost data]# mysqlbinlog --start-date='2016-02-27 11:27:05' mysql-bin.000005(查看mysql二进制日志文件mysql-bin.000005内容,--start
-date开始时间) 
/*!40019 SET @@session.max_insert_delayed_threads=0*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 4
#160227  6:01:39 server id 1  end_log_pos 107 	Start: binlog v 4, server v 5.5.28-log created 160227  6:01:39 at startup
# Warning: this binlog is either in use or was not closed properly.
ROLLBACK/*!*/;
BINLOG '
Q8vQVg8BAAAAZwAAAGsAAAABAAQANS41LjI4LWxvZwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAABDy9BWEzgNAAgAEgAEBAQEEgAAVAAEGggAAAAICAgCAA==
'/*!*/;
# at 107
#160227 11:27:05 server id 1  end_log_pos 177 	Query	thread_id=7	exec_time=0	error_code=0
SET TIMESTAMP=1456543625/*!*/;
SET @@session.pseudo_thread_id=7/*!*/;
SET @@session.foreign_key_checks=1, @@session.sql_auto_is_null=0, @@session.unique_checks=1, @@session.autocommit=1/*!*/;
SET @@session.sql_mode=0/*!*/;
SET @@session.auto_increment_increment=1, @@session.auto_increment_offset=1/*!*/;
/*!\C latin1 *//*!*/;
SET @@session.character_set_client=8,@@session.collation_connection=8,@@session.collation_server=8/*!*/;
SET @@session.lc_time_names=0/*!*/;
SET @@session.collation_database=DEFAULT/*!*/;
BEGIN
/*!*/;
# at 177
#160227 11:27:05 server id 1  end_log_pos 205 	Intvar
SET INSERT_ID=13/*!*/;
# at 205
#160227 11:27:05 server id 1  end_log_pos 331 	Query	thread_id=7	exec_time=0	error_code=0
use jiaowu/*!*/;
SET TIMESTAMP=1456543625/*!*/;
INSERT INTO tutors (Tname,Gender,Age) VALUE ('stu100','M',30)
/*!*/;
# at 331
#160227 11:27:05 server id 1  end_log_pos 358 	Xid = 19
COMMIT/*!*/;
DELIMITER ;
# End of log file
ROLLBACK /* added by mysqlbinlog */;
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
[root@localhost data]# mysqlbinlog --start-date='2016-02-27 11:27:05' mysql-bin.000005 > /root/a.sql(查看mysql二进制日志文件mysql-bin.000005
内容输出重定向到/root/a.sql文件,--start-date开始时间) 
提示:这些内容的信息它里面其实都是记录的是SQL语句,可以把这个结果保存下来,以后可以把a.sql直接导入到另外一个数据库上让它执行一遍,所以通常情况下使用mysqlbinlog
把这个文件内容读取出来而后输出重定向到一个SQL脚步文件里面,在另外一个服务器上执行一遍就能完成即时点还原了,但一定更要注意你的起始位置一定要跟上次恢复的位置相一致;
[root@localhost data]# cd(切换到用户家目录)
[root@localhost ~]# service mysqld restart(重启mysqld服务)
Shutting down MySQL.                                       [  OK  ]
Starting MySQL..                                           [  OK  ]
[root@localhost ~]# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.5.28-log Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> SHOW MASTER STATUS;(查看正在使用二进制日志文件)
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000006 |      107 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

提示:每次服务器重启这个二进制日志文件都会滚动一次,现在变为mysql-bin.000006;

mysql> \q(退出)
Bye

[root@localhost ~]# mysql(连接mysql)
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.5.28-log Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql> FLUSH LOGS;(手动滚动二进制日志文件)
Query OK, 0 rows affected (0.01 sec)

mysql> SHOW MASTER STATUS;(查看正在使用的二进制日志文件)
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000007 |      107 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

mysql> FLUSH HOSTS;(刷新主机)
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW MASTER STATUS;(查看正在使用的二进制日志文件)
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000007 |      177 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

mysql> HELP FLUSH;(查看刷新命令帮助)
Name: 'FLUSH'
Description:
Syntax:
FLUSH [NO_WRITE_TO_BINLOG | LOCAL]
    flush_option [, flush_option] ...

The FLUSH statement has several variant forms that clear or reload
various internal caches, flush tables, or acquire locks. To execute
FLUSH, you must have the RELOAD privilege. Specific flush options might
require additional privileges, as described later.

By default, the server writes FLUSH statements to the binary log so
that they replicate to replication slaves. To suppress logging, use the
optional NO_WRITE_TO_BINLOG keyword or its alias LOCAL.

*Note*: FLUSH LOGS, FLUSH MASTER, FLUSH SLAVE, and FLUSH TABLES WITH
READ LOCK (with or without a table list) are not written to the binary
log in any case because they would cause problems if replicated to a
slave.

The FLUSH statement causes an implicit commit. See
http://dev.mysql.com/doc/refman/5.5/en/implicit-commit.html.

The RESET statement is similar to FLUSH. See [HELP RESET], for
information about using the RESET statement with replication.

URL: http://dev.mysql.com/doc/refman/5.5/en/flush.html

提示:FLUSH LOGS的时候只会滚动二进制日志,错误日志它只会关闭再打开,不会滚动,在从服务器它会滚动中继日志,而从服务器错误日志仍然是关闭再打开,其它日志一个道理;

假如备份完一次想删除某些二进制日志:绝对不能使用rm命令删除,这样mysql服务器会崩溃;

mysql> HELP PURGE
Name: 'PURGE BINARY LOGS'
Description:
Syntax:
PURGE { BINARY | MASTER } LOGS(删除二进制文件)
    { TO 'log_name' | BEFORE datetime_expr }(log_name日志文件名)

The binary log is a set of files that contain information about data
modifications made by the MySQL server. The log consists of a set of
binary log files, plus an index file (see
http://dev.mysql.com/doc/refman/5.5/en/binary-log.html).

The PURGE BINARY LOGS statement deletes all the binary log files listed
in the log index file prior to the specified log file name or date.
BINARY and MASTER are synonyms. Deleted log files also are removed from
the list recorded in the index file, so that the given log file becomes
the first in the list.

This statement has no effect if the server was not started with the
--log-bin option to enable binary logging.

URL: http://dev.mysql.com/doc/refman/5.5/en/purge-binary-logs.html

Examples:
PURGE BINARY LOGS TO 'mysql-bin.010';
PURGE BINARY LOGS BEFORE '2008-04-02 22:46:26';

mysql> PURGE BINARY LOGS TO 'mysql-bin.000003';(删除二进制日志文件mysql-bin.000003之前的日志文件)
Query OK, 0 rows affected (0.01 sec)

mysql> SHOW BINARY LOGS;(查看当前仍然拥有的二进制日志文件)
+------------------+-----------+
| Log_name         | File_size |
+------------------+-----------+
| mysql-bin.000003 |     16214 |
| mysql-bin.000004 |       390 |
| mysql-bin.000005 |       377 |
| mysql-bin.000006 |       150 |
| mysql-bin.000007 |       177 |
+------------------+-----------+
5 rows in set (0.00 sec)

+---------------------------------------------------+-----------+
| Variable_name                                     | Value     |
+---------------------------------------------------+-----------+
| long_query_time                                   | 10.000000 |(慢查询时间)
| max_long_data_size                                | 1048576   |
| performance_schema_events_waits_history_long_size | 10000     |
+---------------------------------------------------+-----------+
3 rows in set (0.00 sec)

mysql> SET GLOBAL slow_query_log=1;(设置全局变量慢查询日志开启)
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW GLOBAL VARIABLES LIKE '%log%';(查看全局变量中间为log的变量)
+-----------------------------------------+----------------------------------------+
| Variable_name                           | Value                                  |
+-----------------------------------------+----------------------------------------+
| back_log                                | 50                                     |
| binlog_cache_size                       | 32768                                  |(二进制日志)
| binlog_direct_non_transactional_updates | OFF                                    |
| binlog_format                           | MIXED                                  |(二进制日志文件格式,MIXED混合格式)
| binlog_stmt_cache_size                  | 32768                                  |
| expire_logs_days                        | 0                                      |
| general_log                             | OFF                                    |(一般查询日志,是否启用一般查询日志,默认都是关闭)
| general_log_file                        | /mydata/data/localhost.log             |(一般查询日志文件记录的目录)
| innodb_flush_log_at_trx_commit          | 1                                      |(innodb事务日志)
| innodb_locks_unsafe_for_binlog          | OFF                                    |
| innodb_log_buffer_size                  | 8388608                                |
| innodb_log_file_size                    | 5242880                                |
| innodb_log_files_in_group               | 2                                      |
| innodb_log_group_home_dir               | ./                                     |
| innodb_mirrored_log_groups              | 1                                      |
| log                                     | OFF                                    |(一般查询日志)
| log_bin                                 | ON                                     |(是不是记录二进制日志)
| log_bin_trust_function_creators         | OFF                                    |
| log_error                               | /mydata/data/localhost.localdomain.err |(错误日志信息,默认在数据目录下,当前主机名加.err的文件)
| log_output                              | FILE                                   |(一般查询日志信息输出到那里,默认是文件,还可以记录到表中)
| log_queries_not_using_indexes           | OFF                                    |
| log_slave_updates                       | OFF                                    |
| log_slow_queries                        | ON                                     |(慢查询日志)
| log_warnings                            | 1                                      |(错误日志,警告信息)
| max_binlog_cache_size                   | 18446744073709547520                   |(binlog文件大小格式的)
| max_binlog_size                         | 1073741824                             |
| max_binlog_stmt_cache_size              | 18446744073709547520                   |
| max_relay_log_size                      | 0                                      |
| relay_log                               |                                        |(中继日志)
| relay_log_index                         |                                        |
| relay_log_info_file                     | relay-log.info                         |
| relay_log_purge                         | ON                                     |
| relay_log_recovery                      | OFF                                    |
| relay_log_space_limit                   | 0                                      |
| slow_query_log                          | ON                                     |(慢查日志开关)
| slow_query_log_file                     | /mydata/data/localhost-slow.log        |(慢查询日志文件存放位置)
| sql_log_bin                             | ON                                     |(手动定义是否启用关闭二进制日志)
| sql_log_off                             | OFF                                    |
| sync_binlog                             | 0                                      |(是不是将日志从缓存同步到磁盘文件,为了加速一般不会理解写到磁盘,
而是记录到内存中的缓存中)
| sync_relay_log                          | 0                                      |
| sync_relay_log_info                     | 0                                      |
+-----------------------------------------+----------------------------------------+
41 rows in set (0.00 sec)