同主機單實例MySQL跨庫同步指定表

需求:ide

同一主機同實例MySQL有A和B兩個庫,如今需實現test1庫中表host和test2庫中表host插入、刪除、更新單向同步。(table01與table02具備相同表結構)spa

解決方案:orm

能夠使用觸發器實現,舉例以下:遞歸

一、建立模擬環境同步

create database test1;it

use test1io

CREATE TABLE `host` (table

 `id` tinyint(4) NOT NULL AUTO_INCREMENT,form

 `host` varchar(20) NOT NULL,class

 `port` tinyint(2) NOT NULL,

 `user` varchar(10) NOT NULL,

 `pwd` varchar(20) NOT NULL,

 PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8

create database test2;

use test2

CREATE TABLE `host` (

 `id` tinyint(4) NOT NULL AUTO_INCREMENT,

 `host` varchar(20) NOT NULL,

 `port` tinyint(2) NOT NULL,

 `user` varchar(10) NOT NULL,

 `pwd` varchar(20) NOT NULL,

 PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8      

二、建立觸發器(若是須要雙向同步操做,在test2上進行相同操做便可,雙向同步時須要注意避免遞歸死循環)

use test1 

DELIMITER //

CREATE TRIGGER Pee_insert_host AFTER INSERT ON host FOR EACH ROW BEGIN INSERT INTO test2.host VALUES (new.id,new.host,new.port,new.user,new.pwd); END;//

CREATE TRIGGER Pee_delete_host AFTER DELETE ON host FOR EACH ROW BEGIN DELETE from test2.host where test2.host.id=old.id; END;//

CREATE TRIGGER Pee_update_host AFTER UPDATE ON host FOR EACH ROW BEGIN UPDATE test2.host SET host=new.host,port=new.port,user=new.user,pwd=new.pwd WHERE test2.host.id=new.id; END;//

DELIMITER ;

三、相關操做

查看觸發器:SELECT * FROM information_schema.`TRIGGERS`;

刪除觸發器:DROP TRIGGER TRIGGER_NAME;

相關文章
相關標籤/搜索