JAVA PreparedStatement 在参数中给出查询

JAVA PreparedStatement give query in parameter

有没有可能做这样的事情:

String sql2 = "";
if (klases.type == 0) {                
      sql2 = " AND (FIND_IN_SET(id, irasai.pirk_vad) OR FIND_IN_SET(id,irasai.pard_vad))";
}

sql = "SELECT * FROM apmokejimai 
      LEFT JOIN irasai ON apmokejimai.apm_invoice_nr = irasai.invoice_nr 
      WHERE (FIND_IN_SET(?, irasai.pirkejas) OR FIND_IN_SET(?, irasai.pirkejas) IS NULL) 
      ? order by apmokejimai.apm_invoice_nr";

ps = conn.prepareStatement(sql);
ps.setInt(1, pirk);
ps.setInt(2, pirk);
ps.setString(3, sql2);

如果 PreparedStatement 参数的类型为 0,我想推送一些 FIND_IN_SET,但问题是它会在查询中设置参数并将其设置在 '' 引号中,有什么办法可以跳过这个吗?或者我只需要为此使用不同的查询?谢谢!

为什么不准备这两个查询并保存在 属性 文件中,并根据条件获取:-

Property File :-
Query1 = SELECT * FROM apmokejimai LEFT JOIN irasai ON apmokejimai.apm_invoice_nr = irasai.invoice_nr WHERE (FIND_IN_SET(?, irasai.pirkejas) OR FIND_IN_SET(?, irasai.pirkejas) IS NULL) AND (FIND_IN_SET(id, irasai.pirk_vad) OR FIND_IN_SET(id,irasai.pard_vad)) order by apmokejimai.apm_invoice_nr
Query2= SELECT * FROM apmokejimai LEFT JOIN irasai ON apmokejimai.apm_invoice_nr = irasai.invoice_nr WHERE (FIND_IN_SET(?, irasai.pirkejas) OR FIND_IN_SET(?, irasai.pirkejas) IS NULL) order by apmokejimai.apm_invoice_nr

String sql = "";
if (klases.type == 0) {                
    sql = "Get the Query1 from Property File";
    ps = conn.prepareStatement(sql);
    ps.setInt(1, pirk);
    ps.setInt(2, pirk);
    ps.setString(3, sql2);
}else{
    sql = "Get the Query2 from Property File";  
    ps = conn.prepareStatement(sql);
    ps.setInt(1, pirk);
    ps.setInt(2, pirk);
}

您需要为准备语句创建一个完整的 SQL 语句。但是,这很容易修复。使用以下 SQL:

sql = "SELECT * FROM apmokejimai 
  LEFT JOIN irasai ON apmokejimai.apm_invoice_nr = irasai.invoice_nr 
  WHERE (FIND_IN_SET(?, irasai.pirkejas) OR FIND_IN_SET(?, irasai.pirkejas) IS NULL) 
   AND (? OR FIND_IN_SET(id, irasai.pirk_vad) OR FIND_IN_SET(id,irasai.pard_vad))
  order by apmokejimai.apm_invoice_nr";

现在你可以只设置 ps.setBoolean(false) 如果你想要它被执行或者 ps.setBoolean(true) 如果你不想它被执行。