You have to do this in two statements:
PreparedStatement update = connection.prepareStatement(
"UPDATE table SET field=? WHERE id=?");
PreparedSTatement insert = connection.prepareStatement(
"INSERT INTO table (id, field) \n" +
" SELECT ?, ? \n" +
" WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=?)";
update.setString(1, "C");
update.setInt(2, 3);
update.executeUpdate();
insert.setInt(1, 3);
insert.setString(2, "C");
insert.setInt(3, 3);
insert.executeUpdate();
connection.commit();
Edit I forgot that Postgres allows multiple SQL statements in one PreparedStatement
:
PreparedStatement stmt = connection.prepareStatement(
"UPDATE table SET field=? WHERE id=?;\n" +
"INSERT INTO table (id, field) \n" +
" SELECT ?, ? \n" +
" WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=?)";
stmt.setString(1, "C");
stmt.setInt(2, 3);
stmt.setInt(3, 3);
stmt.setString(4, "C");
stmt.setInt(5, 3);
stmt.executeUpdate();
connection.commit();
Edit2 the only way I can think of where you only specify the values once is this:
String sql =
"with data (id, col1) as ( \n" +
" values (?, ?) \n" +
"), updated as ( \n" +
" \n" +
" UPDATE foo \n" +
" SET field = (select col1 from data) \n" +
" WHERE id = (select id from data) \n" +
") \n" +
"insert into foo \n" +
"select id, col1 \n" +
"from data \n" +
"where not exists (select 1 \n" +
" from foo \n" +
" where id = (select id from data))";
pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, 3);
pstmt.setString(2, "C");
pstmt.executeUpdate();