需求:
同一主机同实例MySQL有A和B两个库,现在需实现test1库中表host和test2库中表host插入、删除、更新单向同步。(table01与table02具有相同表结构)
解决方案:
可以使用触发器实现,举例如下:
1、创建模拟环境
create database test1;
use test1
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
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
2、创建触发器(如果需要双向同步操作,在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 ;
3、相关操作
查看触发器:SELECT * FROM information_schema.`TRIGGERS`;
删除触发器:DROP TRIGGER TRIGGER_NAME;