我想将下面的 SQL 语句重写成一个动态的 PreparedStatement
java:
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);
特别是我不知道如何将 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);
我的对象,类似的:
@Entity
public class MyEntity {
long id, String name;
}
最佳答案
您必须在两个语句中执行此操作:
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();
编辑 我忘记了 Postgres 允许在一个 PreparedStatement
中使用多个 SQL 语句:
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 我能想到的你只指定值一次的唯一方法是:
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();
关于java - 如何为PreparedStatements改写SQL语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27863606/