简体   繁体   中英

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.

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

为什么不这样做:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM