search
HomeDatabaseMysql TutorialWhat should I do if mysql accidentally deletes the database?

mysql不小心删除数据库的解决办法:首先打开mysql的binlog功能;然后查看二进制日志状态;接着查看二进制日志文件的操作日志;最后通过Bin log恢复数据即可。

What should I do if mysql accidentally deletes the database?

推荐:《mysql视频教程

Mysql的Bin log数据恢复:不小心删除数据库

前言:因为不小心删除了测试机器上Mysql的一整个数据库Schema,因为是测试机所以没有做备份,现在通过MySQL的Bin log方式恢复到删除以前的数据库。

当然做Bin log的数据恢复前提是已经打开Bin log的功能,如果又没做数据备份,又没打开Bin log日志,那你就可能需要考虑快照等其它方式从系统的角度去恢复。

Bin log 常用于数据增量备份和恢复,以及数据库主从复制。如果没有开启,可以通过如下方式打开:

1、打开mysql的binlog功能

mysql是支持增量备份,但要打开mysql的bin log功能。

修改mysql的配置文件。linux是/etc/my.cnf,windows是mysql的安装目录/my.ini
在[mysqld]下面加上log-bin一行代码,如下面:

# Replication Master Server (default)
# binary logging is required for replication
log-bin=mysql-bin

# binary logging format - mixed recommended
binlog_format=mixed。

2、用如下方式查看二进制日志状态:是否开启

mysql> show variables like 'log_%';

3、查看所有二进制日志文件:

mysql> show libary logs;

mysql> show binary logs;
+------------------+-----------+
| Log_name         | File_size |
+------------------+-----------+
| mysql-bin.000001 |       201 |
| mysql-bin.000002 |       351 |
| mysql-bin.000003 |       276 |
| mysql-bin.000004 |       201 |
| mysql-bin.000005 |     16509 |

4、Mysql查看二进制日志文件的操作日志

#mysqlbinlog --start-position=0 /mydata/data/mysql-bin.000089

[root@test mysql]# mysqlbinlog --start-position=0 --stop-position=500 mysql-bin.000091
Warning: option 'start-position': unsigned value 0 adjusted to 4
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;
/*!40019 SET @@session.max_insert_delayed_threads=0*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 4
#151022 18:00:43 server id 1 end_log_pos 107  Start: binlog v 4, server v 5.5.38-log created 151022 18:00:43 at startup
# Warning: this binlog is either in use or was not closed properly.
ROLLBACK/*!*/;
BINLOG '
y7MoVg8BAAAAZwAAAGsAAAABAAQANS41LjM4LWxvZwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAADLsyhWEzgNAAgAEgAEBAQEEgAAVAAEGggAAAAICAgCAA==
'/*!*/;
# at 107
#151022 23:27:50 server id 1 end_log_pos 198  Query  thread_id=2   exec_time=0   error_code=0
SET TIMESTAMP=1445527670/*!*/;
SET @@session.pseudo_thread_id=2/*!*/;
SET @@session.foreign_key_checks=0, @@session.sql_auto_is_null=0, @@session.unique_checks=0, @@session.autocommit=1/*!*/;
SET @@session.sql_mode=1608515584/*!*/;
SET @@session.auto_increment_increment=1, @@session.auto_increment_offset=1/*!*/;
/*!\\\\C utf8 *//*!*/;
SET @@session.character_set_client=33,@@session.collation_connection=33,@@session.collation_server=8/*!*/;
SET @@session.lc_time_names=0/*!*/;
SET @@session.collation_database=DEFAULT/*!*/;
DROP SCHEMA IF EXISTS `pandora`<pre name="code" class="sql">/*!*/;
# at 198
#151022 23:27:50 server id 1 end_log_pos 346  Query  thread_id=2   exec_time=0   error_code=0

5、通过Bin log恢复数据. 因为我整个Schema都删掉了,又没备份,正好开启了bin log日志,所以把历史的bin-log都重新执行了一遍,重新恢复到误删以前的版本,(我这里总共有91个文件,批量处理的):(9999999999999:是为了省掉去查找每一个bin-log日志文件的起始结束位置,设的一个无穷大的数字,简化操作.)

#mysqlbinlog /var/lib/mysql/mysql-bin.000001 --start-position=0 --stop-position=9999999999999 | mysql -uroot -p123456
#mysqlbinlog /var/lib/mysql/mysql-bin.000002 --start-position=0 --stop-position=9999999999999 | mysql -uroot -p123456
#mysqlbinlog /var/lib/mysql/mysql-bin.000003 --start-position=0 --stop-position=9999999999999 | mysql -uroot -p123456
... ...

所以总结结论是:

  1. 1、切记一定要定期备份;
  2. 2、有备份的话恢复也快一点,可以从备份的时间点做增量备份,不需要像我这里从头开始91个文件全部批量跑一遍,当然我用编辑器批量处理的也还算快;
  3. 3、另外一定要打开Bin-log日志,如果没做备份也可以通过Bin-log日志恢复。
  4. 4、操作要小心。

其它:

1、还有个sql_log

mysql> show variables like 'sql_log_%';

Mysql开启关闭sql二进制日志:
mysql> set sql_log_bin=0; //关闭
set session sql_log_bin=0;

2、查找文件位置:

find / -name my.cnf

3、linux 查看当前所在目录的全路径

pwd命令:
/var/lib/mysql

4、查看当前binary log的情况:

mysql>show master status;

5、在my.cnf/my.ini中设定binary logs回滚天数:

expire_logs_days = 7

6、查看Master的bin log日志

mysql> show master logs;
+-----------------+-----------+
| Log_name        | File_size |
+-----------------+-----------+
| log-bin.000001 |        98 | 
+-----------------+-----------+
1 row in set (0.00 sec)
---------------------

The above is the detailed content of What should I do if mysql accidentally deletes the database?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQL: String Data Types and ENUMs?MySQL: String Data Types and ENUMs?May 13, 2025 am 12:05 AM

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

MySQL BLOB: how to optimize BLOBs requestsMySQL BLOB: how to optimize BLOBs requestsMay 13, 2025 am 12:03 AM

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor