foreign key always stays null - java

I need a bit of assistance in getting a connection between my two tables
These are the tables where "idPatient is the foreign key"
I fill the table "tanden" like this
public void addTandenToDatabase(int id, int fdi, String voorstelling, String toestand) {
String insertSql = "insert into tanden(id, fdi, voorstelling, toestand) values (:idVal, :fdiVal, :voorstellingVal, :toestandVal)";
try (Connection con = sql2o.open()) {
con.setRollbackOnException(false);
con.createQuery(insertSql)
.addParameter("idVal", id)
.addParameter("fdiVal", fdi)
.addParameter("voorstellingVal", voorstelling)
.addParameter("toestandVal", toestand)
.executeUpdate();
}
}
Everything is added nicely but the idPatient stays null

You should include idPatient in your insert if you want to set value to it. 'foreign key' doesnot mean that it will be set value automically.

You have to insert idPatient column value into tanden table by taking from patienten table.

Your id column in the tanden table should be set as primary key and autoincrement and you have to set the idPatient in your insert
insert into tanden(idPatient, fdi, voorstelling, toestand) values(:idVal,:fdiVal, :voorstellingVal, :toestandVal)";
(The idPatient you set in the child table already has to exist in the parent table

Related

Auto-Increment of Identity in Netbeans Using DerbyDB

I am trying to insert data into a CUSTOMER table.
private void c_enterActionPerformed(java.awt.event.ActionEvent evt) {
String insertSQL = "insert into CUSTOMER(CUST_ID, CUST_NIC, CUST_FNAME,CUST_LNAME, CUST_EMAIL, CUST_ADDRESS, CUST_PHONE, CUST_IMG) values(?,?,?,?,?,?,?,?)";
try{
ps = con.prepareStatement(insertSQL);
ps.setString(1,c_id_text.getText());
ps.setString(2,c_nic_text.getText());
ps.setString(3,c_fname_text.getText());
ps.setString(4,c_lname_text.getText());
ps.setString(5,c_email_text.getText());
ps.setString(6,c_address_text.getText());
ps.setString(7,c_phone_text.getText());
ps.setString(8,img_path_txt.getText());
ps.execute();
JOptionPane.showMessageDialog(null, "New Customer Inserted\nCongratulations!");
c_id_text.setText("");
c_nic_text.setText("");
c_fname_text.setText("");
c_lname_text.setText("");
c_email_text.setText("");
c_address_text.setText("");
c_phone_text.setText("");
img_path_txt.setText("");
updateTable();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Insertion error: "+e);
}
}
The table was created using:
CREATE TABLE CUSTOMER(
CUST_ID INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
CUST_NIC VARCHAR(14),
CUST_FNAME VARCHAR(20),
CUST_LNAME VARCHAR(25),
CUST_EMAIL VARCHAR(45),
CUST_ADDRESS VARCHAR(60),
CUST_PHONE INTEGER,
CUST_IMG VARCHAR(100));
SELECT * FROM AKASH.CUSTOMER FETCH FIRST 100 ROWS ONLY;
I have disabled the CUST_ID text as shown. It's telling me "Attempt to modify an identity column 'CUST_ID'.
Now, for claritfication: I know what is happening. But I don't know how to fix it.
I tried to remove ps.setString(1,c_id_text.getText()); , that didn't work.
I also tried to remove CUST_ID from String insertSQL... , but to no avail.
If I try to input data from the SQL using "Insert row" button, it works and the CUST_ID column displays ""
Found my mistake. Solved after commenting out
ps.setString(1,c_id_text.getText());
and c_id_text.setText("");
as well as removing CUST_ID form the insertSQL line of code.

SQLite how to overwrite same data

I am working on an android project, basicli I have some x,y coordinates in my sqlite but when I add a new data I want to check the data and if there is same data overwrite it.
public void DBCreate(){
SQLITEDATABASE = openOrCreateDatabase("LatLongDatabase", Context.MODE_PRIVATE, null);
SQLITEDATABASE.execSQL("CREATE TABLE IF NOT EXISTS myTable(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, mCurrentLocationLAT VARCHAR,mCurrentLocationLONG VARCHAR);");
}
public void SubmitData2SQLiteDB(){
SQLiteQuery = "INSERT INTO myTable (mCurrentLocationLAT, mCurrentLocationLONG) VALUES('"+mCurrentLocation.getLatitude()+"','"+mCurrentLocation.getLongitude()+"');";
SQLITEDATABASE.execSQL(SQLiteQuery);
Toast.makeText(CampaignActivity.this,"OK", Toast.LENGTH_LONG).show();
}
You need to use UPDATE query to update the row with PRIMARY_KEY if data exists or INSERT new row.
Since your table have a PRIMARY_KEY as id, you can check if row exists as below.
SELECT EXISTS(SELECT 1 FROM myTable WHERE id='ROW_ID');
If above query returns 1, then data exists, and you need to use UPDATE query as below, else use INSERT query.
UPDATE myTable SET mCurrentLocationLAT=value1, mCurrentLocationLONG=value2 WHERE id='ROW_ID';
SQLite has an INSERT OR REPLACE statement which can be shortened just to REPLACE which will insert a new row if it doesn't exist, or replace (delete then insert) a row if it does exist. Read the docs to learn about primary key constraints and how to handle them.
REPLACE INTO positions (title, min_salary)
VALUES
('Full Stack Developer', 140000);

Getting foreign key and refering table name of particular database table from metadata DatabaseMetaData using JAVA class

I am writing java class to get all connection database objects(tables). I have used
rs = meta.getExportedKeys(conn.getCatalog(), null, "account_adjustment");
while (rs.next()) {
String fkTableName = rs.getString("FKTABLE_NAME");
String fkColumnName = rs.getString("FKCOLUMN_NAME");
int fkSequence = rs.getInt("KEY_SEQ");
}
which is giving parent table and it's column linked this asked table(account_adjustment)
and also I tried
rs1 = meta.getImportedKeys(conn.getCatalog(), null, "account_adjustment");
while (rs1.next()) {
String fkTableName = rs1.getString("FKTABLE_NAME");
String fkColumnName = rs1.getString("FKCOLUMN_NAME");
int fkSequence = rs1.getInt("KEY_SEQ");
}
which is giving current table(account_adjustment) table and it's foreign key column name
but I want table name with which this foreign key is linked
I have got solution bt in other way not using java,, instead of getting values using java i executed query to 'information_schema' (which is there by default in MySQL) database and 'REFERENTIAL_CONSTRAINTS' table to get all reference of respective tables of required database

How to get super table information in java?

My database had a lot of parent and child tables.The tables contains the foreign key which has the link with the parent table.I wants to get the information of parent table of the child table using java?How can I achieve that?
For ex,consider the student and mark table,
The student table contains the information like studentID,name.
studentID-Primary key
The marks table contains the markId,studentId,Sub1,sub2,sub3 etc
markId-Primarykey
studentID-Foreignkey refers Student table
My table creation queries are,
CREATE TABLE `Student12` (
`studentId` SMALLINT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`studentId`)
)
ENGINE = InnoDB;
CREATE TABLE `Marks` (
`markId` SMALLINT NOT NULL AUTO_INCREMENT,
`subject1` SMALLINT NOT NULL,
`subject2` SMALLINT NOT NULL,
`studentId` SMALLINT NOT NULL,
PRIMARY KEY (`markId`),
CONSTRAINT `FK_Marks_Student` FOREIGN KEY `FK_Marks_Student` (`studentId`)
REFERENCES `Student12` (`studentId`)
ON DELETE RESTRICT
ON UPDATE RESTRICT
)
ENGINE = InnoDB;
If I give the mark table name as input, how can I get its parent or super table name student and information about student table?Any help should be appreciable.
It totally depends on the way tables are created. Foreign keys are not mandatory to create, they could be a simple column in one table with no explicit relationship to the other table. If you are very sure that the links are created explicitly (the foreign keys are defined) then you could use information_schema. But if there is no foreign key defined (which is true in most of the databases I have seen), then there is no way for you to find the links inside the database. You have to look into the code (if there is any available) and try to find a clue.
The JDBC DatasetMetaData interface provides a couple of methods that may help. (The following text is copied from the javadoc.
ResultSet getExportedKeys(String catalog, String schema, String table)
Retrieves a description of the foreign key columns that reference the given table's primary key columns (the foreign keys exported by a table).
ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable)
Retrieves a description of the foreign key columns in the given foreign key table that reference the primary key or the columns representing a unique constraint of the parent table (could be the same or a different table).
Of course, these can only work if the relevant columns have been declared as foreign keys in the SQL table DDL.
You can use the DatabaseMetaData to retrieve informations about foreign keyes
and the referenced Tables. Im not sure if it works with all kinds of MySql Tables.
The principle is to use the follwing code (not tested) to retrieve information about the super tables
ResultSet rs = null;
DatabaseMetaData dm = conn.getMetaData( );
// get super tables of table marks
ResultSet rs = dm.getSuperTables( null , null, "marks" );
while( rs.next( ) ) {
System.out.println(String.format("Table Catalog %s", rs.getString("TABLE_CAT") );
System.out.println(String.format("Table Schema %s", rs.getString("TABLE_SCHEM") );
System.out.println(String.format("Table Name %s", rs.getString("TABLE_NAME") );
System.out.println(String.format("Table Name %s", rs.getString("SUPERTABLE_NAME") );
}
You can use thes informations to get additional informations about the referenced table
and the foreigen and referenced primary keys:
ResultSet rs = dm.getCrossReference( null , null , "student" , null , null , "marks" );
System.out.println(String.format("Exported Keys Info Table %s.", "marks"));
while( rs.next( ) ) {
String pkey = rs.getString("PKCOLUMN_NAME");
String ptab = rs.getString("PKTABLE_NAME");
String fkey = rs.getString("FKCOLUMN_NAME");
String ftab = rs.getString("FKTABLE_NAME");
System.out.println("primary key table = " + ptab);
System.out.println("primary key = " + pkey);
System.out.println("foreign key table = " + ftab);
System.out.println("foreign key = " + fkey);
}
And finally you can retrieve the information about the super table by
ResultSet rs = dm.getTables(null,null,"student" ,null);
System.out.println("Table name:");
while (rs.next()){
String table = rs.getString("TABLE_NAME");
System.out.println(table);
}

How to get an automatically incremented column value when inserting a row into a table in mysql using java?

How can I insert into table1 like: INSERT INTO table1 (description) VALUES ('Some test description here'); and have it return the automatically incremented ID so that I can then insert a row into table2? The description is not guaranteed to be unique. I am using a Java PreparedStatement to insert the value currently with execute()
I have the following table structure:
CREATE TABLE table1 (
table1ID INTEGER NOT NULL AUTO_INCREMENT,
description VARCHAR(255) NOT NULL,
CONSTRAINT PK_table1 PRIMARY KEY (table1ID)
);
CREATE TABLE table2 (
table1ID INTEGER NOT NULL,
personID INTEGER NOT NULL,
CONSTRAINT PK_table2 PRIMARY KEY (table1ID, personID)
);
ALTER TABLE table2 ADD CONSTRAINT FK_table1_table2
FOREIGN KEY (table1ID) REFERENCES table1 (table1ID);
ALTER TABLE table2 ADD CONSTRAINT FK_table2_person
FOREIGN KEY (personID) REFERENCES person (personID);
run this query right after the insert completes succesfully: SELECT LAST_INSERT_ID()
Try this:
PreparedStatement st = con.prepareStatement(
"Insert into table1 (name) values ('test desc')",
Statement.RETURN_GENERATED_KEYS);
st.executeUpdate();
ResultSet rs = st.getGeneratedKeys();
if(rs.next())
{
int data = rs.getRow();
int id = rs.getInt(1);
}
Observe values of data & id.
You don't need to fire insert & select queries separately.

Categories