TheHaruWhoCodes
TheHaruWhoCodes

Reputation: 67

How do I write a Delete SQL Statement in Java for Tables with composite key?

I'm 99% this question has been answered somewhere, but I can't seem to find what I'm looking for. So far, I've been writing my sql statement to delete a row from a table in java like this (this for a table called crime where the primary key is called CrimeId. The CrimeId is taken from the UI)

private DatabaseAPI db;
PreparedStatement st=db.connection.prepareStatement("DELETE FROM crime WHERE CrimeId = '"+Integer.parseInt(txtCrimeId.getText())+"';");

How would I write the where statement for a composite key? Like, for a table called charges in which the key is both CrimeID and CriminalID?

Upvotes: 0

Views: 545

Answers (4)

Yevhen Zhovtonoh
Yevhen Zhovtonoh

Reputation: 241

I believe next code should work for you

PreparedStatement st=db.connection.prepareStatement("DELETE FROM crime WHERE CrimeId = ? and CriminalID = ?");
st.setInt(1, Integer.parseInt(txtCrimeId.getText()));
st.setInt(2, Integer.parseInt(txtCriminalID.getText()));
st.executeUpdate();

Upvotes: 1

qdongxu
qdongxu

Reputation: 414

Something like below:

PreparedStatement st=db.connection.prepareStatement(
  "DELETE FROM crime WHERE CrimeId = ? AND CriminalID = ?" );
st.setInt(1, Integer.parseInt(txtCrimeId.getText() );
st.setInt( 2, Integer.parseInt(txtCriminaId.getText());

Upvotes: 1

Jakob
Jakob

Reputation: 1895

You need to use AND. With AND you combine to conditions.

Read this for more information

So then your code looks like

DELETE FROM charges WHERE CrimeId = 'YourCrimeID' AND CriminalID = 'YourCriminalID' ;

Just replace YourCriminalID and YourCrimeID.

Upvotes: 0

Duncan Small
Duncan Small

Reputation: 1

DELETE FROM charges WHERE CrimeId = '____' AND CriminalID = '____' ;

Is this what you were looking for?

Upvotes: 0

Related Questions