Java preparedstatement cannot insert data to mysql child table with foreign key - foreign-keys

I am stuck with my parent-child mysql tables. I'm using preparedstatements in Java programming language. But I'm only successful with inserting data to my parent table. However, I can't insert data to my child table after executing another insert statement.
These are the glimpse of my tables:
tbl_patient:
ID (primary key)
patientName (primary key)
address
contact
tbl_admission:
ID (primary key)
admitDate
patientName (foreign key referenced from tbl_patient)
When I executed my statements for inserting a new patient, it became successful and I got the result stored to my tbl_patient table. However, my problem started when I executed my preparedstatements for tbl_admission since it cannot add data to my tbl_admission. Instead, I get the following error:
Cannot add or update a child row: a foreign key constraint fails (hms_mdh/admission, CONSTRAINT FK_admission_1 FOREIGN KEY (ID, patientName) REFERENCES tbl_patient (ID, patientName))
I really don't know what's happening here. Can I get any help? Thanks.
This is my sample sql in my child table - the admission table:
CREATE TABLE admission (
ID int(11) NOT NULL auto_increment,
admitID varchar(45) NOT NULL default '',
admitDate varchar(45) NOT NULL default '',
patientID varchar(45) NOT NULL default '',
entrance varchar(45) NOT NULL default '',
doctor varchar(45) NOT NULL default '',
initialDiagnosis varchar(45) NOT NULL default '',
recommend varchar(100) NOT NULL default '',
patientName varchar(45) NOT NULL default '',
PRIMARY KEY (ID),
KEY FK_admission_1 (ID,patientName),
CONSTRAINT FK_admission_1 FOREIGN KEY (ID, patientName) REFERENCES tbl_patient (ID, patientName)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='InnoDB free: 11264 kB; (ID patientName) REFER `hms_mdh/t'
And this is the parent table--the patients:
CREATE TABLE tbl_patient (
ID int(11) NOT NULL auto_increment,
patientID varchar(45) NOT NULL default '',
gender varchar(45) NOT NULL default '',
birthday varchar(45) NOT NULL default '',
chiefcomplain varchar(100) NOT NULL default '',
entrance varchar(45) NOT NULL default '',
patientName varchar(45) NOT NULL default '',
PRIMARY KEY (ID,patientName)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Related

mariadb won't create foreign key

I think I'm using the right syntax for MariaDB, but my foreign key constraint is not being created.
Here's the create table DDL:
CREATE TABLE items (
id INT auto_increment primary key,
description TEXT NOT NULL
);
CREATE TABLE item_events (
id INT NOT NULL,
calendar_event_guid TEXT(255) NOT NULL,
foreign key item_events_id_fk (id) REFERENCES items (id)
);
Then, when I ask MariaDB to show me what I created, I get this:
+-------------+-----------------
| Table | Create Table +-------------+-----------------
| item_events | CREATE TABLE `item_events` (
`id` int(11) NOT NULL,
`calendar_event_guid` text COLLATE utf8_unicode_ci NOT NULL,
KEY `item_events_id_fk` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
+-------------+-----------------
or, just showing the DDL:
CREATE TABLE `item_events` (
`id` int(11) NOT NULL,
`calendar_event_guid` text COLLATE utf8_unicode_ci NOT NULL,
KEY `item_events_id_fk` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Notice that it only created a "KEY", not a foreign key. The items table is correctly created.
Surely, this is really simple :)

Django and mariadb not working with istartswith correctly using german umlauts

the following query should only return all cities starting with "Ö" (German umlaut).
letter = 'Ö'
City.objects.filter(name__istartswith=letter)
But it returns cities starting with O and Ö.
I use django 1.11 and mariadb.
I allready set COLLATE on that table to utf8_bin but this haven't changed the behavior within django.
This is the simplified SQL query
SELECT `cities_city`.`name` FROM `cities_city` WHERE `cities_city`.`name` LIKE "Ö%";
and here the SHOW CREATE TABLE output:
SHOW CREATE TABLE `cities_city`
-> ;
+-------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| cities_city | CREATE TABLE `cities_city` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) CHARACTER SET utf8 NOT NULL,
`slug` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`name_std` varchar(200) CHARACTER SET utf8 NOT NULL,
`location` point NOT NULL,
`population` int(11) NOT NULL,
`elevation` int(11) DEFAULT NULL,
`kind` varchar(10) CHARACTER SET utf8 NOT NULL,
`timezone` varchar(40) CHARACTER SET utf8 NOT NULL,
`country_id` int(11) NOT NULL,
`region_id` int(11) DEFAULT NULL,
`subregion_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `cities_city_country_id_2f07e352_uniq` (`country_id`,`region_id`,`subregion_id`,`id`,`name`),
KEY `cities_city_b068931c` (`name`),
KEY `cities_city_16c3f481` (`name_std`),
KEY `cities_city_region_id_0227cdac_fk_cities_region_id` (`region_id`),
KEY `cities_city_subregion_id_9fbab97d_fk_cities_subregion_id` (`subregion_id`),
CONSTRAINT `cities_city_country_id_779ae117_fk_cities_country_id` FOREIGN KEY (`country_id`) REFERENCES `cities_country` (`id`),
CONSTRAINT `cities_city_region_id_0227cdac_fk_cities_region_id` FOREIGN KEY (`region_id`) REFERENCES `cities_region` (`id`),
CONSTRAINT `cities_city_subregion_id_9fbab97d_fk_cities_subregion_id` FOREIGN KEY (`subregion_id`) REFERENCES `cities_subregion` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11468436 DEFAULT CHARSET=utf8 COLLATE=utf8_bin |
+-------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
The problem is a subtle one.
The clue is here:
SELECT * FROM information_schema.`COLUMNS` WHERE table_name = 'cities_city';
The explanation...
`name` varchar(200) CHARACTER SET utf8 NOT NULL,
is COLLATE utf8_general_ci because that is the default collation for utf8.
This table default:
) ENGINE=InnoDB AUTO_INCREMENT=11468436 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
gives utf8_bin to any newly added rows.
Perhaps you did the obvious ALTER TABLE to change to _bin? Instead:
ALTER TABLE cities_city
CONVERT TO CHARACTER SET utf8
COLLATE utf8_bin;
this will go into each string column and make the change. Note that indexes (etc) must be rebuilt when the collation changes.

RegEx to remove lines from MySQL dump

CREATE TABLE `transaction` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`description` text NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `description` (`description`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
How can I remove FULLTEXT line from MySQL dump above and comma on the line before so it looks something like this:
CREATE TABLE `transaction` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The removal should be easy using sed but I'm not sure how to remove this comma on the line above so the dump is successfully imported:
sed -i '/FULLTEXT KEY.*/d' dump.sql
Sometimes there is also more columns with FULLTEXT index:
CREATE TABLE `entity` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`company_name` varchar(255) NOT NULL DEFAULT '',
`description` text NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `company_name` (`company_name`),
FULLTEXT KEY `description` (`description`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Sed script:
#!/bin/bash
sed -e '/FULLTEXT/d' |
sed -ne '
/ENGINE=InnoDB/!{H}
/ENGINE=InnoDB/{x; s/,[ \t]*$//; p; }
${g;p;}
'
Input:
CREATE TABLE `transaction` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`description` text NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `description` (`description`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `entity` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`company_name` varchar(255) NOT NULL DEFAULT '',
`description` text NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `company_name` (`company_name`),
FULLTEXT KEY `description` (`description`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Sample Run:
/home/user> ./1.sed < input
CREATE TABLE `transaction` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `entity` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`company_name` varchar(255) NOT NULL DEFAULT '',
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
sed is for simple substitutions on individual lines, that is all. For anything else you should use awk for clarity, brevity, portability, efficiency, robustness and most other desirable qualities of software. All of the sed constructs to do anything other than s, g, and p (with -n) became obsolete in the mid-1970s when awk was invented and exist today just for mental exercise.
Given this input:
$ cat file
CREATE TABLE `transaction` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`description` text NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `description` (`description`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `entity` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`company_name` varchar(255) NOT NULL DEFAULT '',
`description` text NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `company_name` (`company_name`),
FULLTEXT KEY `description` (`description`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
With GNU awk for multi-char RS:
$ awk -v RS=',\\s*FULLTEXT[^\n]*)' -v ORS= '1' file
CREATE TABLE `transaction` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `entity` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`company_name` varchar(255) NOT NULL DEFAULT '',
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Since you are using GNU sed (for -i) I assume you will have no problem using GNU awk and if you need inplace editing add -i inplace at the start.
awk -vRS=";" 'NF{gsub(/),\n +FULLTEXT.*)/,")\n)",$0);$0=$0";"}1' file

How to update and set unit_id to be NULL, unit id is foreign key from unit table

How to update and set unit_id to be NULL, unit id is foreign key and I need to set to be NULL
CREATE TABLE troops
(
id serial NOT NULL,
unit_id integer,
type integer NOT NULL,
level integer NOT NULL,
CONSTRAINT troops_pkey PRIMARY KEY (id),
CONSTRAINT troops_unit_id_fkey FOREIGN KEY (unit_id)
REFERENCES units (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE
)
WITH (
OIDS=FALSE
);
I have tried to update troops and set unit_id to be NULL ( I put NULL not 0 in pqxx statement in C++ ) but I get error like
insert or update on table "troops" violates foreign key constraint "troops_unit_id_fkey"
DETAIL: Key (unit_id)=(0) is not present in table "units".
When I try from pgadmin I can set unit_id to be NULL in troops but pqxx ( from c++ code I try to update) converts NULL to 0, how to solve this ?

One to many mapping in Zend Framwork 2 with doctrine

I am trying to make a page where i handle my invoces. I have the invoice data in one tables and the invoice rows in another table. The tables looks as follows:
CREATE TABLE IF NOT EXISTS `Invoices` (
`I_Id` int(10) NOT NULL AUTO_INCREMENT,
`I_Number` int(4) NOT NULL,
`I_ClientId` int(10) NOT NULL,
`I_ExtraText` text NOT NULL,
PRIMARY KEY (`I_Id`)
) ENGINE=InnoDB
CREATE TABLE IF NOT EXISTS `InvoiceRows` (
`IR_Id` int(10) NOT NULL AUTO_INCREMENT,
`IR_InvoiceId` int(10) NOT NULL,
`IR_Price` int(10) NOT NULL,
`IR_Vat` smallint(2) unsigned NOT NULL,
`IR_Quantity` int(10) NOT NULL,
`IR_Text` varchar(255) NOT NULL,
PRIMARY KEY (`IR_Id`),
KEY `IR_InvoiceId` (`IR_InvoiceId`)
) ENGINE=InnoDB
Here is my mapping:
class Invoice {
/**
* #ORM\OneToMany(targetEntity="Row", mappedBy="invoice" ,cascade={"persist"})
*/
protected $rows;
}
class Row {
/**
* #ORM\ManyToOne(targetEntity="Invoice", inversedBy="rows", cascade={"persist"})
* #ORM\JoinColumn(name="IR_InvoiceId", referencedColumnName="I_Id")
**/
private $invoice;
}
I have been trying to follow the example at the doctrine docs on how to setup a One-To-Many, Bidirectional mapping. This is then connect with Zend Framework 2 and form collections. Pulling data works very good. I get all the rows of each invoice.
My Problem is when i want to write back to the database and save my changes. When i try to save i get the following error:
An exception occurred while executing 'INSERT INTO
MVIT_ADM__InvoiceRows (IR_InvoiceId, IR_Price, IR_Vat, IR_Quantity,
IR_Text) VALUES (?, ?, ?, ?, ?)' with params
{"1":null,"2":320,"3":0,"4":1,"5":"Learning your dog to sit"}:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'IR_InvoiceId' cannot be null
What have i done wrong? When checking the data from the post value is not empty.
Edit: Full source can be found at Github
It seems IR_InvoiceId null, it expect the Id of Invoices (I_Id) value, so make sure while you are inserting the data in InvoiceRows table then here pass the Invoices (I_Id) value as IR_InvoiceId as you mention table relation..
Best Of Luck!
Saran