Can't delete row from a database - java

I'm working at some school project and my job here is to make a delete button for that list view in Java FX, but the problem is that when i want to proceed that it shows me this error. I tried some solutions, but none of them worked.
so here's the code
#FXML
private void removeStudentOnClick(ActionEvent event) throws IOException, SQLException{
ModelEditStudent student=(ModelEditStudent)tables.getSelectionModel().getSelectedItem();
String sql="DELETE FROM student WHERE nr_indeksu=?";
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Usuwanie studenta");
alert.setHeaderText(null);
alert.setContentText("Czy na pewno chcesz usunąc tego studenta z listy?");
Optional <ButtonType> action = alert.showAndWait();
if(action.get() == ButtonType.OK){
tables.getItems().removeAll(tables.getSelectionModel().getSelectedItem());
try{
try (Connection myConn = ConnectionManager.getConnection()) {
try (PreparedStatement st = myConn.prepareStatement(sql)) {
st.setString(1, student.getNr_indeksu());
st.executeUpdate();
}
myConn.close();
}
}catch (SQLException e){
System.out.println(e);
}
}
and there's the error:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Cannot delete or update a parent row: a foreign key constraint fails
(`wu`.`oceny`, CONSTRAINT `oceny_ibfk_3` FOREIGN KEY (`nr_indeksu`)
REFERENCES `student` (`nr_indeksu`))
All the point of this operation is about selecting the row and removing from the database after pressing a button. By now it works only for the listview, but it doesn't remove records from the database.
Anyone got an idea how make it work?

I believe the problem is in your DB schema. try fixing the foreign keys dependencies.I mean the value of nr_indeksu exists in another table of your DB.

You have a table called oceny which has a column nr_indeksu that contains student ids. You have created a foreign key constraint on that table, which requires those student ids to match up with something in the student table.
If you try to delete something in the student table that's referenced by the oceny table, you will get this error, because otherwise, it would leave the database in a state where the oceny table references a student that doesn't exist.
There are a number of solutions to this. You will need to think about what should actually happen in this case - what do you want to have happen to the oceny rows when you delete a matching student.
One option would be for you to change the foreign key to make it do a "cascade delete" - that is, the oceny automatically gets deleted in the same transaction as the student. There's some information here on how to do that.

Related

Synchronized deleting from two tables by expired date

I have three tables in my database:
First one of COMPANY that includes id, name and email.
Second - COUPON that includes id, title, dates, price etc...
Third - join table COMPANY_COUPON that includes id of the companies and id of the coupons which they own.
In java, I have a method that deletes expired coupons using:
DELETE FROM COUPON WHERE END_DATE < CURRENT_DATE
But after deleting expired coupons, I still have their id in COMPANY_ COUPON join table, how can I solve this?
#Override
public void removeExpiredCoupons() throws CouponSystemException {
String delete = "DELETE FROM COUPON WHERE END_DATE < CURRENT_DATE";
Connection connection = pool.getConnection();
try (PreparedStatement pstmt = connection.prepareStatement(delete)) {
pstmt.executeUpdate();
// This line can be removed
System.out.println("All expired coupos are removed.");
} catch (SQLException e) {
throw new CouponSystemException("Removing expired coupons is failed. ", e);
} finally {
pool.returnConnection(connection);
}
}
It sounds like you currently have no foreign key constraints defined from COMPANY_COUPON to COUPON (nor to COMPANY). That is undesirable, because it results exactly in the problem you describe.
If you want records in COMPANY_COUPON to get automatically deleted if the record is deleted, you need to define a foreign key constraint from COMPANY_COUPON to COUPON and make it on delete cascade.
For example you can add one with
alter table COMPANY_COUPON
add constraint fk_company_coupon_coupon
foreign key (COUPON_ID) references COUPON (ID) on delete cascade
You should do something similar to COMPANY.
you COULD:
delete the records in the company_coupon table before deleting the records in the coupon table:
first get a list of the expired id's by retrieving result set of expired id's:
select id from coupon where END_DATE < CURRENT_DATE
then loop through the result set to delete records of each id:
delete from company_coupon where id = idFromLoop
lastly delete the records from the coupon table:
delete from coupon where END_DATE < CURRENT_DATE
you SHOULD:
google "foreign key on delete cascade" to see how to use a foreign key to delete associated records across tables.

why cant i "update" data to the database from netbeans interface.

<html>
<body>
<pre>
geting a error when click on the update button as : "com.microsoft.sqlserver.jdbc.SQLServerException: Violation of PRIMARY KEY constraint 'PK_customer'. Cannot insert duplication key in object 'dbo.Customer'. The duplication key value is ()."
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://localhost:1433;databaseName=77OOP062;user=sa;password=hnd";
Connection conn= DriverManager.getConnection(url);
String value1=jTextFieldCustomerName.getText();
String value2=jTextFieldHomeAddress.getText();
String value3=jTextFieldNIC.getText();
String value4=jTextFieldEmailAddress.getText();
String value5=jTextFieldContactNo.getText();
String value6=jLabel7.getText();
pst=conn.prepareStatement("update Customer set CustomerName=?,HomeAddress=?,NIC=?,EmailAddress=?,ContactNo=?,InvoiceNo=?");
pst.setString(1,value1);
pst.setString(2,value2);
pst.setString(3,value3);
pst.setString(4,value4);
pst.setString(5,value5);
pst.setString(6,value6);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Güncellendi");
}catch(Exception e){;
JOptionPane.showMessageDialog(null, e);
}
distable();
}
</pre>
</body>
</html>
geting a error when click on the update button as : "com.microsoft.sqlserver.jdbc.SQLServerException: Violation of PRIMARY KEY constraint 'PK_customer'. Cannot insert duplication key in object 'dbo.Customer'. The duplication key value is ()."
since your update statement doesn't include a where clause, your statement tries to update all rows in the table and since you've put primary key column NIC in the update statement, it also get's overwritten but after the first write rdbms realizes your putting the same value in NIC column(which isn't allowed as pk must be unique) and thus gives you the error.
use a where clause to filter rows u want to update and don't update the pk.

foreign key always stays null

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

solution with JAVA or Postgres for insertion in database

(source: hostingpics.net)
how can I add a new customer or supplier?, last time I was using this class for one table "customer":
Code:
public int addnewcustomer(){
int idcust;
DBConnection eConnexion = new DBConnection();
try {
//Statement state = eConnexion.getConnexion().createStatement();
String sql = "INSERT INTO customer(name_cust, num_cust, adress_cust, city_cust , tel_cust, ref_cust)";
sql+= "VALUES (?,?,?,?,?,?)";
PreparedStatement insertQuery = eConnexion.getConnexion().prepareStatement(sql);
insertQuery.setString(1,Name_cust);
insertQuery.setString(2,Num_cust);
insertQuery.setString(3,Adress_cust);
insertQuery.setString(4,City_cust );
insertQuery.setString(5,Tel_cust);
insertQuery.setString(6,Ref_cust);
insertQuery.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
//JOptionPane.showMessageDialog(null,"Erreur:the addition is not performed with Succee!");
idcust = 0;
}
eConnexion.closeConnection();
idcust= Services.getLastInsertedId("customer","id_customer");
return idcust;
}
Currently, I attach all tables with new table "person". All tables now extend "person", I tried to add new customer with super variables "person" but I'm stuck in filling foreign key "id_pers FK".
First you need to persist a person into your database. After a successful(!) persist, you can query for the id the database used to insert the data. Most databases also provide a method to directly retrieve the used id after an insert.
After you have successfully persisted the person you can use the id for the foreign key column.
You may consider using a transaction for these actions, as there should never be a person persisted without a customer/employee whatever extending the persons data.
With a transaction, you can rollback the previous actions, for example if something goes wrong during the insertion of the customer.

MySQL Transactional delete and Java

I've got tables like this:
Table A:
`id | name`
Table B:
`id | A_id | ....`
A_id is a foreign key to Table A, the Engine is InnoDB
This is the code that fails:
String[] cleanupQueries = new String[] { "DELETE FROM B WHERE A_id = (SELECT id FROM A WHERE name = 'test')",
"DELETE FROM A WHERE name = 'test'" };
Connection connection;
try {
connection = DriverManager.getConnection(getConnectionString());
connection.setAutoCommit(false);
} catch (SQLException e) {
throw new RuntimeException("Error establishing a database connection!");
}
try {
for(String cleanupQuery : cleanupQueries) {
PreparedStatement statement = connection.prepareStatement(cleanupQuery);
statement.executeUpdate(); //FAILS WHEN EXECUTING THE SECOND QUERY
}
} catch(SQLException e) {
throw new RuntimeException("Error while executing the queries in the transactional context!");
}
try {
connection.commit();
} catch (SQLException e) {
rollback(connection);
throw new RuntimeException("Error while comitting!");
}
The Exception i get is:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails ('DATABASE/TABLE', CONSTRAINT 'FK_B_A' FOREIGN KEY ('FK_A') REFERENCES 'A' ('ID') ON DEL)
The database doesn't let me delete A while there are still B's left, but the first query deleted all B's. I want to delete all B's and the A they reference only completely.
I don't want to change the Tables to have cascading deletes. What shall i do to get the code working?
Cause for error is
The Foreign Key has referenced to the table A id so if you would like to delete the F_Key , first you should delete the Child references values of that foreign keys then only its possible to delete the parent.
Correct me if 'm wrong..
Simply add the cascade is true while deleting the foreign key constraint.The child table entry is automatically deleted when you delete the original parent entry.
Try:
"DELETE FROM B WHERE A_id = (SELECT id FROM A WHERE name IN 'test')"
Since the child rows are deleted in the same transaction, the deleted rows are still visible and thus the parent rows could not be deleted.
This may be because of the transaction isolation setting on the connection. I would try different levels and see which one allows it.

Categories