MYSQL - How to insert data to another server DB table - mysql

I am trying to insert data to Second server's DB table after inserted to First server' table like below structure,
Second server :
use SecondServerDB;
CREATE TABLE user (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`age` smallint(6) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB;
After created table in Second sever, I have created table in First server like below,
First server :
use FirstServerDB;
CREATE TABLE remote_user2 (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`age` smallint(6) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=FEDERATED
DEFAULT CHARSET=latin1
CONNECTION='mysql://MysqlUserName:MysqlUserPassword#SecondServer.MyDomain.com:3306/SecondServerDB/user';
After created FEDERATED table in second server, Created triggers in same server like below,
DELIMITER $$
CREATE TRIGGER remote_insert_Testing AFTER INSERT ON remote_user2 FOR EACH ROW
BEGIN
INSERT INTO user (ID,name, age) VALUES (NEW.ID,NEW.name, NEW.Age);
END $$
DELIMITER ;
If i run insert query like below,
INSERT INTO remote_user2 (ID,name, age) VALUES (1,'Name',27);
Then it shows, Error Code: 1146. Table 'FirstServerDB.user' doesn't exist.
where am i doing mistake?
Note : I googled and found out What i am trying is possible. How to create trigger to insert data to a database on another server for possible

Try using the fully qualified table names in your trigger:
DELIMITER $$
CREATE TRIGGER remote_insert_Testing
AFTER INSERT ON FirstServerDB.remote_user2 FOR EACH ROW
BEGIN
INSERT INTO SecondServerDB.user (ID,name, age)
VALUES (NEW.ID, NEW.name, NEW.Age);
END $$
DELIMITER ;
If you don't mind moving the data through a normal query, you can try the following:
INSERT INTO SecondServerDB.user (ID, name, age)
SELECT ID, name, age
FROM FirstServerDB.remote_user2

Related

How to find the recently modified row in tables of a MySQL database?

I have a MySQL database (employee) consists of 5 tables. How to find the recently modified row by column name id in tables?
I tried to find the table using the coding below. It works fine.
USE
information_schema;
SELECT DISTINCT TABLE_NAME
FROM TABLES
WHERE
UPDATE_TIME IS NOT NULL AND UPDATE_TIME < NOW() AND TABLE_SCHEMA = 'employee'
Please help to find the row by column name id (all tables have this column name as identifier) in that table.
I think the work around for this problem is to create a trigger that will insert a record into a different table
CREATE TABLE `table_row_monitor` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tbl` varchar(100) DEFAULT NULL,
`col` varchar(100) DEFAULT NULL,
`val` int,
`dtecreated` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`process_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TRIGGER IF EXISTS chk_pickup_contact_for_delivery;
DELIMITER $$
CREATE TRIGGER `[table_name]_log_row_insert` AFTER INSERT ON `[table_name]` FOR EACH ROW
BEGIN
INSERT INTO table_row_monitor (tbl, col, val)
SELECT '[table_name]', 'id', MAX(id) FROM `[table_name]`;
END$$
DELIMITER ;
just replace the [table_name]

MySQL trigger - Trigger table name interpreted as field

I am having an issue with a trigger I have put in a database I am building. It is the only trigger in the database. Here are the two tables being used.
Client Table
create table client (
clientNum INT(5) not null auto_increment,
clientName TEXT(30) not null,
clientEmail VARCHAR(64) not null,
clientGender CHAR(1) not null,
clientDOB DATE not null,
clientAddress TEXT(50),
clientPhone VARCHAR(12) not null,
hasInsurance CHAR(1) not null,
clientBalanceOwed DECIMAL(10,2),
clientLastDateVisited DATE,
clientNextVisitDate DATE,
primary key (clientNum));
Insurance Table
create table insurance(
insuranceNum INT(5) not null auto_increment,
cardNum INT(16),
policyNum INT(6),
policyHolder TEXT(30),
clientNum INT(5),
primary key (insuranceNum),
foreign key (clientNum) references client(clientNum));
The idea for the following trigger is to only create an insurance row when a client is added to the database that has the 'hasInsurance' field set to 'y'. Then, once that client has been added, create a new insurance row with the clientNum set to the clientNum that was just added.
The Trigger
delimiter $$
create trigger New_Insurance_Row after insert on client
for each row
begin
if(client.hasInsurance = 'y') then
insert into insurance (clientNum) values (NEW.clientNum);
end if;
end$$
Everything up to this point works as intended, until you try to insert a new client into the table and call the trigger. Once I try and add the following line of code:
The Insert Statement
insert into client(clientName, clientEmail, clientGender, clientDOB,
clientAddress,
clientPhone, hasInsurance, clientBalanceOwed, clientLastDateVisited,
clientNextVisitDate)
values
('Darcy Watts','dwatts#email.com','m','1996-5-9','Belfast, Charlottetown
PEI','123-222-3333','y','400.77','2017-8-12','2019-9-6');
When I try and run this I am met with this error:
#1109 - Unknown table 'client' in field list
So from what I've learned over the last few hours is that this error usually happens when you put the '`' (backtick) on a variable or table name, MySQL thinks that entry is part of a field list or something along that line. So I changed the trigger to just be 'client' by itself and I still got an error. Dropped the old database and everything. One more thing, the insert statement does work by itself if the trigger has not been entered yet.
Any help would be appreciated! Thanks!
I guess your hasInsurance should be from the new record.
...
if(new.hasInsurance = 'y') then
insert into insurance (clientNum) values (NEW.clientNum);
end if;
...
--
DB Fiddle (provided by GMB)

Insert bulk of records into MySQL with stored procedure

I have some millions records and I want to insert them as some batches to increase the speed.
I have a table as follows:
CREATE TABLE `source_names` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`source_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `source_name_UNIQUE` (`source_name`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=latin1;
and in one step I want to add 500 source_name in source_names like this:
insert ignore into source_names (source_name)
values ('a01'),('a02'),...,('a500')
up to here there is no problem.
In Qt I have a QString which is like this (of course the IDE is not important in this question):
QString totalSourceNames="('a01'),('a02'),...,('a500')";
I want to insert this QString into source_names table by insertPro stored procedure and these commands:
query.prepare("CALL insertPro(:source_names)");
query.bindValue(":source_names",totalSourceNames);
query.exec()
and my stored procedure is:
CREATE DEFINER=`root`#`localhost` PROCEDURE `insertPro`(
IN source_names text
)
BEGIN
insert ignore into source_names(source_name) values (source_names);
END
By MySQL inserts just one row and concatenates all 500 values in one value. I know this is because of parenthesis in front of values (...) in above code but removing parenthesis makes an error in MySQL.
How can I insert 500 records with stored procedure?

MySQL: Integrity error when inserting into database

So, I have this one column in my table that gets filled by a trigger when a new entry is inserted.
CREATE TABLE `users` (
`idusers` int(11) NOT NULL AUTO_INCREMENT,
`uid` char(64) DEFAULT NULL,
`uname` varchar(80) NOT NULL,
`password` char(128) NOT NULL,
`mail` varchar(120) NOT NULL,
PRIMARY KEY (`idusers`),
UNIQUE KEY `uname_UNIQUE` (`uname`),
UNIQUE KEY `mail_UNIQUE` (`mail`),
UNIQUE KEY `uid_UNIQUE` (`uid`)
);
DELIMITER $$
TRIGGER `flask`.`users_BEFORE_INSERT` BEFORE INSERT ON `users` FOR EACH ROW
BEGIN
set new.uid = sha2(new.idusers, 256);
END$$
DELIMITER ;
The problem now is that when I try to add a new row (only have a test one yet because of the error), in the trigger the value of new.idusers is somehow always 0 instead of the current auto_increment value.
What do I need to change in my trigger code so that the value used for generating the uid is the actual id and not always 0?
Since idusers is an AUTO_INCREMENT field, its value is known only after the record is inserted in the table.
Use an AFTER INSERT trigger instead of a BEFORE INSERT trigger, and update the newly inserted record:
DELIMITER $$
CREATE TRIGGER `flask`.`users_AFTER_INSERT` AFTER INSERT ON `users` FOR EACH ROW
BEGIN
UPDATE users SET uid = sha2(NEW.idusers, 256) WHERE idusers = NEW.idusers;
END $$
DELIMITER ;

How to create trigger to insert data to a database on another server

I have 2 mysql databases on different hosts, want trigger after insert data to one database it inserted to another . I'm new in mysql , in sql server I can create linked server and do it . But how to do in mysql ?
Both databases have similar table
CREATE TABLE `tsttbl` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`age` smallint(6) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
For you to be able to proceed with this, you must first ensure that both servers have identical configurations. And to accomplish what you are wanting to do, it is possible to use the FEDERATED storage engine on both servers, in conjunction with triggers, to allow each server to update the other server's database.
You need to create the local table that is federated to the user table on the other server. So, if a record already exists on the other server, but not here, we want the insert on the other server to throw an error that prevents us from creating the record here... as opposed to creating a record here with what would be a conflicting ID;
CREATE TABLE remote_user (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`age` smallint(6) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
CONNECTION='mysql://username:pass#the_other_host:port/schema/user';
Then you can create your trigger;
DELIMITER $$
CREATE TRIGGER user_bi BEFORE INSERT ON user FOR EACH ROW
BEGIN
INSERT INTO remote_user (ID,name, age) VALUES (NEW.ID,NEW.name, NEW.Age);
END $$
CREATE TRIGGER user_bu BEFORE UPDATE ON user FOR EACH ROW
BEGIN
UPDATE remote_user
SET ID= NEW.ID,
name= NEW.name
age = NEW.Age
WHERE ID = OLD.ID;
END $$
CREATE TRIGGER user_bd BEFORE DELETE ON user FOR EACH ROW
BEGIN
DELETE FROM remote_user
WHERE ID= OLD.ID;
END $$
DELIMITER ;