如何为PreparedStatements重写SQL语句?

mem*_*und 1 java sql postgresql jdbc

我想将folling的SQL语句重写为动态PreparedStatementjava:

UPDATE table SET field='C' WHERE id=3;
INSERT INTO table (id, field)
       SELECT 3, 'C'
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);
Run Code Online (Sandbox Code Playgroud)

特别是我不知道如何将SELECT 3, 'C'行重写为动态语句.

UPDATE table SET name=:name WHERE id=:id
INSERT INTO table (id, name)
       SELECT 3, 'C'  <-- how could I rewrite these values to take the dynamic values from PreparedStatement?
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);
Run Code Online (Sandbox Code Playgroud)

我的对象,类似:

@Entity
public class MyEntity {
   long id, String name;
}
Run Code Online (Sandbox Code Playgroud)

a_h*_*ame 7

你必须在两个陈述中这样做:

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();
Run Code Online (Sandbox Code Playgroud)

编辑我忘了Postgres允许多个SQL语句合二为一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();
Run Code Online (Sandbox Code Playgroud)

Edit2是我能想到你只指定一次值的唯一方法是:

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();
Run Code Online (Sandbox Code Playgroud)