如何用不同的值替换多个字符?

时间:2019-05-15 21:16:32

标签: java

我有一个字符串,我想在其中替换字符“?”我有一个数组,要替换的值。
这是我的字符串:

FROM lineorder A INNER JOIN date B 
ON (B.d_datekey = A.lo_orderdate)  
WHERE 
  (A.lo_discount >= ? AND A.lo_discount <= ?) AND (A.lo_quantity < ?) 
  AND (B.d_year = ?)

这是我的数组,其值为 [1,3,25,1993]

我想得到以下结果:

FROM lineorder A INNER JOIN date B 
ON (B.d_datekey = A.lo_orderdate)  
WHERE 
  (A.lo_discount >= 1 AND A.lo_discount <= 3) AND (A.lo_quantity < 25) 
  AND (B.d_year = 1993)

我该怎么做?

3 个答案:

答案 0 :(得分:1)

如果您使用的是JDBC,并且具有PreparedStatement,则可以执行以下操作:

String sql = "FROM lineorder A INNER JOIN date B \n" +
                        "ON (B.d_datekey = A.lo_orderdate)  \n" +
                            "WHERE \n" + "  (A.lo_discount >= ? AND A.lo_discount <= ?) AND (A.lo_quantity < ?) \n" +
                            "  AND (B.d_year = ?)";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        int[] arrayOfInts = {1,3,25,1993};

        for(int i = 0; i < arrayOfInts.length; i++) {
            preparedStatement.setInt(i + 1, arrayOfInts[i]); // the i index goes from the first "?" to the last, setting their values with the array value at that index. i + 1 because PreparedStatements indexes start from 1.
        }

答案 1 :(得分:0)

由于我们专门讨论sql,请确保您未使用直接字符串替换,而应该对输入数据进行清理并使用准备好的语句。通过不走这条路线,您可以进行潜在的SQL注入。

以下是使用准备好的语句的常见示例:https://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/

答案 2 :(得分:0)

如果您不想以JDBC方式进行操作,则可以使用这样的字符串操作


import java.util.regex.Pattern;

public class A
{
  public static void main(String [] args)
  {
      String s = "FROM lineorder A INNER JOIN date B ON (B.d_datekey = A.lo_orderdate)  WHERE (A.lo_discount >= ? AND A.lo_discount <= ?) AND (A.lo_quantity < ?) AND (B.d_year = ?) " ; 

      int [] a =  {1, 3, 25, 1993} ; 

      for(int i : a ) 
      {
        s = s.replaceFirst(Pattern.quote("?"),Integer.toString(i)) ; 
      }

      System.out.println(s) ;      
  }

}