afzalex
afzalex

Reputation: 8652

How to provide an expression as parameter in `PreparedStatement`

This table is representing a radio button.

id    | radio_id    | value    | is_selected
------|-------------|----------|-------------
1     | 10          | one      | false
2     | 10          | two      | false
3     | 10          | three    | true

I could run following query to select another radio.

UPDATE TABLE radios SET is_selected = (id = 1) WHERE radio_id = 10

Using this query I was also assuring that only 1 radio box is selected.

id    | radio_id    | value    | is_selected
------|-------------|----------|-------------
1     | 10          | one      | true
2     | 10          | two      | false
3     | 10          | three    | false

But I am unable to do the same thing with PreparedStatement

PreparedStatement ps = con.prepareStatement("UPDATE TABLE radios SET is_selected = ? WHERE radio_id = ?");
ps.setObject(1, "(id = 1)");
ps.setInt(2, 10);

But then I am getting error that String cannot be converted to boolean. How to provide an expression as parameter in prepared statement.

Upvotes: 3

Views: 384

Answers (2)

Dmytro Plekhotkin
Dmytro Plekhotkin

Reputation: 1993

PreparedStatement ps = 
    con.prepareStatement("UPDATE TABLE radios SET is_selected = (id = ?) WHERE radio_id = ?");
ps.setInt(1, 1);
ps.setInt(2, 10);

Upvotes: 3

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Why not just do:

con.prepareStatement("UPDATE radios SET is_selected = (id = 1) WHERE radio_id = ?");

Upvotes: 1

Related Questions