I have a BASH program that inserts into my DB somes lines.
Unfortunately, when MYSQL encounter an error(especially foreign key constraint errors), the entire SQL request stops.
Isn't there a way to skip the lines where the foreign key constraint doesn't apply, and keep adding the others?
insertVtigerInfos() {
$mysql -h $db_address -u $db_user -p$db_passwd $db_name -e "delete from $db_vtiger_name;load data local infile '$vtiger_temporary_file' REPLACE INTO TABLE $db_vtiger_name fields terminated by ';'"
}
----------------------démarrage---------------------------------
Tue May 6 16:03:13 CEST 2014
ERROR 1452 (23000) at line 1: Cannot add or update a child row: a foreign key constraint fails (`RH2QUALIF`.`info_vtiger`, CONSTRAINT `info_vtiger_ibfk_1` FOREIGN KEY (`nom_caisse`) REFERENCES `definition_ip_switch` (`nom_caisse`) ON DELETE CASCADE ON UPDATE CASCADE)
-------------------------fin------------------------------------
Tue May 6 16:03:14 CEST 2014
Updating thread with sample :
Table toward whom the foreign key constraint applies :
+-------------+------------+
| nom_caisse | quat_octet |
+-------------+------------+
| BCP | NULL |
| CEA | NULL |
Table having the foreign key constraint :
+-----------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------+-------+
| code_site | varchar(32) | NO | PRI | NULL | |
| nom_caisse | varchar(32) | NO | MUL | NULL | |
| ip_routeur | varchar(32) | NO | | NULL | |
Data trying to be inserted :
131001M0;CEA;<ip>
131001G0;CEALS;<ip>
When mysql tries to insert the rows, the 1st is OK, the 2nd is not (because CEALS is not in the table which the foreign key is.
But mysql doesn't add ANY row because he found one not matching... I just want it to add the 1st row...
The only solution i found is to do that :
$mysql -f -h $db_address -u $db_user -p$db_passwd $db_name -e "SET foreign_key_checks=0;delete from $db_vtiger_name;load data local infile '$vtiger_temporary_file' REPLACE INTO TABLE $db_vtiger_name fields terminated by ';';SET foreign_key_checks=1;"
and then sending another request which delete the rows according to the foreign key.
delete from info_vtiger where NOT EXISTS ( select nom_caisse from definition_ip_switch where definition_ip_switch.nom_caisse=info_vtiger.nom_caisse ) ;
Unfortunately, the foreign key constraint is no more useful in this case.
posting it as a solution, if anyone have some other ways to do it...
If your requirement is just to insert new records but not replace to existing records then you can use as per below:
$mysql -h $db_address -u $db_user -p$db_passwd $db_name -e "delete from $db_vtiger_name;load data local infile '$vtiger_temporary_file' INSERT IGNORE INTO TABLE $db_vtiger_name fields terminated by ';'"
Related
This is my shell script to insert csv data into my mysql table but we are getting the below error.
"ERROR 1452 (23000) at line 1: Cannot add or update a child row: a
foreign key constraint fails (inv_impact.asset_ext_warranty,
CONSTRAINT fk_asset_ext_warranty FOREIGN KEY (vendor_id)
REFERENCES vendor (vendor_id) ON DELETE NO ACTION ON UPDATE NO
ACTION)"
Shell script is like:
#!/bin/bash
IFS=,
while read offering auth_no DOP price extend_from extend_to status vendor_id
do echo "INSERT INTO asset_ext_warranty(offering, auth_no, DOP, price, extend_from, extend_upto, status, vendor_id) VALUES ('$offering','$auth_no','$DOP','$price','$extend_from','$extend_upto','$status','$vendor_id');" done < warr-ext.csv | mysql -uroot -p'pass' dbname;
while the parents table has the vendor_id with the referencing values
vendor_id | vendor_name | person_name | phone_no | mail_id | vendor_detail |
+-----------+----------------------------+--------------------+---------------+---------------------------+------------------------------------------------------------------------------------+
| 1 | nsiah | Hshiwq | 0981002364 | suajs#yahoo.co.in | NULL |
| 2 | Dell International service | Dell | 1800-425-4026 | NULL | NULL |
| 3 | Integral system ltd | Mamata | NULL | NULL | NULL
the child row(vendor_id) in csv file has the same value as parents row .
I have tried everything I can think of but I am still having problems creating a table.
I have a user table with a primary key username
+---------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
| username | varchar(50) | NO | PRI | NULL | |
| administrator | tinyint(1) | YES | | NULL | |
| fullname | text | YES | | NULL | |
| description | text | YES | | NULL | |
| password | varchar(60) | NO | | NULL | |
+---------------+-------------+------+-----+---------+-------+
and I want to create a new table like this:
CREATE TABLE sessions (
created_at DATETIME,
updated_at DATETIME,
token VARCHAR(50) NOT NULL,
username VARCHAR(50),
PRIMARY KEY (token),
FOREIGN KEY(username) REFERENCES users (username)
);
but I get a nasty error:
ERROR 1215 (HY000): Cannot add foreign key constraint
I usually find this error is caused by a mismatch in the data type of the pk/fk pair but this time both are clearly varchar(50) so it looks like the problem is elsewhere.
I have also tried this just in case:
CREATE TABLE sessions (
created_at DATETIME,
updated_at DATETIME,
token VARCHAR(50) NOT NULL,
username varchar(50) NOT NULL, #<- ***added not null***
PRIMARY KEY (token),
FOREIGN KEY(username) REFERENCES users (username)
);
mysql>SHOW ENGINE INNODB STATUS
LATEST FOREIGN KEY ERROR
2016-08-03 15:13:23 a46fcb70 Error in foreign key constraint of table savesdev/sessions:
FOREIGN KEY(username) REFERENCES users (username)):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
It seems the error is raised under two circumstances:
1) When there is a mismatch (which I have ruled out)
column types in the table and the referenced table do not match for constraint.
2) When there is no suitable index on the referenced column
Cannot find an index in the referenced table where the referenced columns appear as the first columns
I think both of these are covered so what's the deal?
Can anyone spot my error?
Maybe your columns username have different charset can you try this :
ALTER TABLE sessions MODIFY username VARCHAR(50) CHARACTER SET utf8;
ALTER TABLE users MODIFY username VARCHAR(50) CHARACTER SET utf8;
As suggested by #Graeme Stuart here is a link to see how we can check the charterer set of a database / table or a column : How do I see what character set a MySQL database / table / column is?
ALL,
igor#IgorDellGentoo ~ $ isql myodbc-5.2-test root wasqra
+---------------------------------------+
| Connected! |
| |
| sql-statement |
| help [tablename] |
| quit |
| |
+---------------------------------------+
SQL> use draft;
SQLRowCount returns 0
SQL> ALTER TABLE owners ADD FOREIGN KEY id REFERENCES leagues(id);
[ISQL]ERROR: Could not SQLExecute
SQL>
What am I doing wrong?
Also, for some reason I can't create a foreign key thru the mySQL-Workbench when creating the table.
There is no "Add" button or "+" sign to add this constraint. And there is no reaction on the right click.
Could someone please point me to the right direction?
I have Workbench version 6.3.4.0 on Gentoo Linux.
SQL> show tables;
+-----------------------------------------------------------------+
| Tables_in_draft |
+-----------------------------------------------------------------+
| leagues |
| owners |
+-----------------------------------------------------------------+
SQLRowCount returns 2
2 rows fetched
SQL> SELECT * FROM leagues;
+-----------+-----------------------------------------------------------------------------------------------------+-----------+------------+-----------+-----------+-----------+-------------+
| id | name | drafttype | scoringtype| roundvalue| leaguetype| salary | benchplayers|
+-----------+-----------------------------------------------------------------------------------------------------+-----------+------------+-----------+-----------+-----------+-------------+
+-----------+-----------------------------------------------------------------------------------------------------+-----------+------------+-----------+-----------+-----------+-------------+
seems you are using id as a foreign key use proper column instead
ALTER TABLE owners
ADD COLUMN FOREIGNID INT NOT NULL;
ALTER TABLE owners
ADD FOREIGN KEY (FOREIGNID) REFERENCES leagues(ID);
On a simple table insert MYSQL constnatly fails on the 581st row and throws the following error:
INSERT interface (interface,status,description,deviceID) VALUES("Et34-10G","down","nodesc","1977")
INSERT interface (interface,status,description,deviceID) VALUES("Et35-10G","down","nodesc","1977")
INSERT interface (interface,status,description,deviceID) VALUES("Et36-10G","down","nodesc","1977")
INSERT interface (interface,status,description,deviceID) VALUES("Et37-10G","up","chic-02","1977")
INSERT interface (interface,status,description,deviceID) VALUES("Et38-10G","up","chic-06","1977")
INSERT interface (interface,status,description,deviceID) VALUES("Et39-10G","up","chic-07","1977")
DBD::mysql::db do failed: Cannot add or update a child row: a foreign key constraint fails (`dcss`.`interface`, CONSTRAINT `deviceID` FOREIGN KEY (`id`) REFERENCES `device` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) at ./import_intstate_into_dcssdb.pl line 27.
It always fails on inserting the 581th row.
| 576 | Et34-10G | down | nodesc | 1977 |
| 577 | Et35-10G | down | nodesc | 1977 |
| 578 | Et36-10G | down | nodesc | 1977 |
| 579 | Et37-10G | up | chic-02 | 1977 |
| 580 | Et38-10G | up | chic-06 | 1977 |
+-----+--------------+--------+-------------------------------------------------------------------------
580 rows in set (0.00 sec)
I cannot understand why it was able to insert the previous rows with the same deviceID (1977) but throws at error consistently on the 581st row.
I have tested this and gotten the same results piping in the raw SQL statements.
-bash-4.1$ mysql -u root -p dcss < test.sql
Enter password:
ERROR 1452 (23000) at line 581: Cannot add or update a child row: a foreign key constraint fails (`dcss`.`interface`, CONSTRAINT `deviceID` FOREIGN KEY (`id`) REFERENCES `device` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
I am at a loss to explain this. The parent table has this id in it so there is not reason it should be failing on a constraint issue.
mysql> SELECT * FROM device WHERE id=1977;
+------+-------------------------+---------------+------------------+--------------+--------+--------+--------------+---------------+------+-------+
| id | fqdn | ipv4addr | ipv6addr | datacenterID | typeID | make | model | serial_number | os | shell |
+------+-------------------------+---------------+------------------+--------------+--------+--------+--------------+---------------+------+-------+
| 1977 | ls03.router | 10.10.255.210 | unk | 1 | 2 | ARISTA | DCS-7050S-64 | 1234567 | EOS | unk |
+------+-------------------------+---------------+------------------+--------------+--------+--------+--------------+---------------+------+-------+
1 row in set (0.00 sec)
Mate, can you look closer at the data that you try to insert as row 581?
I guess there is some special symbol there that is preventing the correct way to cast the string "1977" to integer 1977.
Try to insert it like that:
INSERT interface (interface,status,description,deviceID) VALUES("Et39-10G","up","chic-07", 1977);
Tell me how this is working for you.
I am using dbf2mysql library http://manpages.ubuntu.com/manpages/natty/man1/dbf2mysql.1.html to port some data to mysql, but when i try to view the inserted records nothing is inserted.
Here is the command I am running:
$ dbf2mysql -vvv -q -h localhost -P password -U root smb/C_clist.DBF -d opera_dbf -t pricelists -c
Opening dbf-file smb/C_clist.DBF
dbf-file: smb/C_clist.DBF - Visual FoxPro w. DBC, MySQL-dbase: opera_dbf, MySQL-table: pricelists
Number of records: 12
Name Length Display Type
-------------------------------------
CL_CODE 8 0 C
CL_DESC 30 0 C
CL_CURR 3 0 C
CL_FCDEC 1 0 N
Making connection to MySQL-server
Dropping original table (if one exists)
Building CREATE-clause
Sending create-clause
CREATE TABLE pricelists (CL_CODE varchar(8) not null,
CL_DESC varchar(30) not null,
CL_CURR varchar(3) not null,
CL_FCDEC int not null)
fields in dbh 4, allocated mem for query 279, query size 139
Inserting records
Inserting record 0
LOAD DATA LOCAL INFILE '/tmp/d2mygo04TM' REPLACE INTO table pricelists fields terminated by ',' enclosed by ''''
Closing up....
then in mysql, the tables are created with the correct fields types, but no data:
mysql> use opera_dbf;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> describe pricelists;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| CL_CODE | varchar(8) | NO | | NULL | |
| CL_DESC | varchar(30) | NO | | NULL | |
| CL_CURR | varchar(3) | NO | | NULL | |
| CL_FCDEC | int(11) | NO | | NULL | |
+----------+-------------+------+-----+---------+-------+
4 rows in set (0.13 sec)
mysql> select * from pricelists;
Empty set (0.00 sec)
mysql>
What am I missing?
I removed the -q option and it works
-q dbf2mysql: "Quick" mode. Inserts data via temporary file using
'LOAD DATA INFILE' MySQL statement. This increased insertion
speed on my PC 2-2.5 times. Also note that during whole 'LOAD
DATA' affected table is locked.