mysql 的 init_connect 变量是每一个客户端连上数据库服务器时执行的一组数据,这组数据能够是一个或者多个sql语句。mysql
A string to be executed by the server for each client that connects. The string consists of one or more SQL statements, separated by semicolon characters.sql
mysql 的 binlog 日志用于记录全部更新了数据库内容的sql语句,以事件的形式保存。数据库
The server's binary log consists of files containing “events” that describe modifications to database contents.vim
CREATE DATABASE accesslog; CREATE TABLE accesslog.accesslog ( `id` INT (11) PRIMARY KEY auto_increment, `time` TIMESTAMP, `localname` VARCHAR (30), `matchname` VARCHAR (30) )
GRANT SELECT ON accesslog.* to root@localhost IDENTIFIED BY 'password'
在 mysql 配置文件里(my.cnf或者my.ini)里[mysqld]里添加以下设置服务器
init_connect='INSERT INTO accesslog.accesslog VALUES(connection_id(),now(),user(),current_user());'
而后重启数据库。工具
mysql> show variables like 'log_bin';
若是没有开启则开启binlog 打开mysql配置文件日志
vim /etc/my.cnf
在[mysqld] 区块添加以下设置code
logb-bin=mysql-bin
mysql-bin是日志文件的前缀名 而后重启服务器生效server
binlog 日志默认存储在数据目录,即 mysql 配置文件里的 datadir 目录。若是log-bin写了完整的目录,则日志文件在相应目录。 在目录下能看到以下文件就是啦 事件
mysql 自带的工具 mysqlbinlog 用于导出binlog日志,格式以下:
/mysql/bin/mysqlbinlog --database=test --start-date="2016-03-25 00:00:00" --stop-date="2016-03-28 15:00:00" /mysql/data/mysql-bin.000071 > test
--database
: 指定数据库名
--start-date
: 开始时间
--stop-date
: 结束时间
若是star-date 到 stop-date 跨越了好几个binlog文件能够经过mysql-bin.000*的方式模糊指定。 这样就导出了 2016-03-25 00:00:00 到 2016-03-28 15:00:00 之间执行的全部修改过数据的sql语句了。 格式以下 160328 18:33:29是执行时间 thread id 是客户端链接数据的id,即上面存储到accelog的id 同时还能够这样提取出某张表的sql语句
cat test.sql | grep ‘TABLE_NAME’ > xx.sql
如上,经过查找binlog能找到客户端链接数据库的id,去查前面创建的accesslog表就能够找到是哪一个用户操做的。 另外,当发生了误操做以后能够利用该方法恢复数据。 假如2016-3-25 13:10:00 发生了误操做。首先找到最近的一次数据库备份,假如是2016-03-01 00:00:00 那么则导出从2016-03-01 00:00:00到2016-3-25 13:10:00之间的binlog记录,而后删除其中的误操做语句(必定要删除)。接下来执行数据库备份,而后执行binlog导出的sql记录便可将数据库恢复至最新版本。