我想将folling 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;
}
答案 0 :(得分: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();
编辑我忘了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();
答案 1 :(得分:1)
你会这样做:
SELECT ?, ?
然后使用生成的PreparedStatement
对象,绑定参数:
myPreparedStatement.setLong(1, 3); //The first ? found
myPreparedStatement.setString(2, "C");
当您进行循环或使用通过方法传递给您的变量时,这更有利,而不是您已经在代码中知道的常量(如果出现的话)