GentleDevil
GentleDevil

Reputation: 25

Trouble with SQL query

I'm new in database and sql, and just trying to figure it all out in Java, but I got stuck with some minor problem, I'm trying to remove one record in db, with id that is given as method parameter, like this, but it's not working

@Override
public void removeCustomer(int number) {
    Statement statement = null;
    try {
        statement = connection.createStatement();
        statement.executeUpdate("DELETE FROM Customers WHERE id='number'");
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try{
            if(statement != null) statement.close();
        } catch (SQLException e ) {
            e.printStackTrace();
        }
    }
}

It does work, when I write in SQL query " ... WHERE id='2'"; But I want to be able to pass the number from method parameter. Anyone could help?

Upvotes: 1

Views: 59

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59968

You can use PreparedStatement like so :

try(PreparedStatement stm = connection.createStatement("DELETE FROM Customers WHERE id=?")){
    stm.setInt(1, number);
    stm.executeUpdate();
}
//.. catch and finally 

Note

It does work, when I write in SQL query " ... WHERE id='2'";

If in case your id is a varchar you can pass a string to the statement by using setString instead of setInt, but I don't suggest to use string for id

Upvotes: 4

Related Questions