MySQL --init-file 參數可以讓 memory 表的固定數據永不丟失

衆所周知, memory 存儲引擎的表,數據只保留在內存,重啓 MySQL 服務或主機後,表數據會丟失。

但可以在啓動  MySQL 服務時,通過  --init-file 參數,指定需要執行插入數據到 memory 表的 sql 文件或在該sql文件中引用 load data infile 通過直接裝載文件的方式,將固定格式的文本數據加載進 MySQL表,如下:

1、在 insert_tmem.sql 文件中加入要插入到  memory 表 t_mem 的sql語句,如:

insert into mytest.t_mem  select * from t1;


或在 insert_tmem.sql 文件中加入 load data infile 方式裝載文本文件的數據,如下:

[root@dg-st tmp]# cat insert_tmem.sql
load data infile '/root/tmp/t_mem.txt' replace into table mytest.t_mem
character set utf8 fields terminated by ',' enclosed by ''
lines terminated by '\n' (id,names,addr) set upd_time=current_timestamp;


2、其中,/root/tmp/t_mem.txt 要裝載的源數據文本文件數據格式如下:

[root@dg-st tmp]# cat t_mem.txt
1,chen,mm
2,hong,gz
3,quan,cn
4,samdy,us


3、啓動 mysql 服務時,通過指定 --init-file=/root/tmp/insert_tmem.sql 參數,啓動 mysql 後,會自動裝載數據到 memory 表 t_mem,如下:

[root@dg-st tmp]# mysqld_safe --user=mysql --init-file=/root/tmp/insert_tmem.sql &


4、啓動 mysql ,發現數據已經成功裝載進來了:

mysql> select * from t_mem;
+------+-------+------+---------------------+
| id   | names | addr | upd_time            |
+------+-------+------+---------------------+
|    1 | chen  | mm   | 2017-09-19 08:59:48 |
|    2 | hong  | gz   | 2017-09-19 08:59:48 |
|    3 | quan  | cn   | 2017-09-19 08:59:48 |
|    4 | samdy | us   | 2017-09-19 08:59:48 |
+------+-------+------+---------------------+
4 rows in set (0.00 sec)



5、t_mem  的存儲引擎類型是 memory:

mysql> select table_name,engine from information_schema.tables where table_name='t_mem'; 
+------------+--------+
| table_name | engine |
+------------+--------+
| t_mem      | MEMORY |
+------------+--------+

mysql> show create table t_mem \G   
*************************** 1. row ***************************
       Table: t_mem
Create Table: CREATE TABLE `t_mem` (
  `id` int(11) DEFAULT NULL,
  `names` varchar(100) COLLATE utf8_bin DEFAULT NULL,
  `addr` varchar(200) COLLATE utf8_bin DEFAULT NULL,
  `upd_time` datetime DEFAULT NULL,
  KEY `idx_tmem_id` (`id`)

) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_bin


(完)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章