实战:从Mysql数据库frm文件中,提取表结构建立SQL语句

需求python

在某些特殊的场景下,例如你的mysql数据库没法启动,须要你将表的ibd文件拷贝到另外一个数据库中,恢复业务数据库,恢复业务数据的前提,是你须要在另外一个数据库中,建立好如出一辙的表结构。这时你就须要从Mysql数据库的frm文件中,提取表结构建立sql语句。mysql

要想读取frm文件中的表结构,你须要先安装mysql的工具集rpm包,我安装的是mysql-utilities-1.6.5-1.el7.noarch.rpm这个版本,这个包能够从mysql官方网站下载,他依赖mysql-connector-python包,因此也须要从官网下载。sql

安装过程以下所示数据库

[root@mysql ~]# yum install mysql-connector-python-2.1.8-1.el7.x86_64.rpm
[root@mysql ~]# yum install mysql-utilities-1.6.5-1.el7.noarch.rpm

有的朋友可能有疑问,既然你的mysql数据库已经没法启动了,那mysqlfrm可否提取到表结构建立sql语句呢,下面就来实战测试一下ide

检查是否有mysqld服务进程工具

[mysql@mysql ~]$ ps -ef|grep -i mysqldmysql
74835  70672  0 16:45 pts/1    00:00:00 grep --color=auto -i mysqld

使用mysqlfrm提取表结构测试

[mysql@mysql testdb]$ mysqlfrm --diagnostic /data/mysql/data/3306/testdb/test1.frm
# WARNING: Cannot generate character set or collation names without the --server option.
# CAUTION: The diagnostic mode is a best-effort parse of the .frm file. As such, it may not identify all of the components of the table correctly. This is especially true for damaged files. It will also not read the default values for the columns and the resulting statement may not be syntactically correct.
# Reading .frm file for /data/mysql/data/3306/testdb/test1.frm:
# The .frm file is a TABLE.
# CREATE TABLE Statement:

CREATE TABLE `testdb`.`test1` (
  `id` int(11) NOT NULL,
  `name1` char(40) NOT NULL,
  `name2` char(80) NOT NULL,
PRIMARY KEY `PRIMARY` (`id`)
) ENGINE=InnoDB;

#...done.

能够看到,已经提取到test1的表结构建立sql语句了,那来看看,提取到的语句是不是正确的。网站

[root@localhost] 16:53:24 [testdb]>show tables;
+------------------+
| Tables_in_testdb |
+------------------+
| test1            |
+------------------+
1 row in set (0.00 sec)

[root@localhost] 16:53:32 [testdb]>show create table test1\G;
*************************** 1. row ***************************
       Table: test1
Create Table: CREATE TABLE `test1` (
  `id` int(11) NOT NULL,
  `name1` char(10) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `name2` char(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
1 row in set (0.03 sec)

ERROR:
No query specified

对比一下原始表结构和提取出来的表结构,是否是发现有不同的地方,这是由于mysqlfrm在不链接数据库提取表结构sql语句时,是没法知道用什么字符集的。在这个测试表,用的字符集是utf8mb4,一个字符占用4个字节长度,因此在这里,还须要将char,varchar的长度除4,才是正确的表结构sql语句。code

相关文章
相关标签/搜索