2012-12-06 23 views
0

的规格为这个分配如下:如何将SELECT语句到一个公共的静态

  • 找到所有的嵌入SQL语句和执行不已经使用常量嵌入式SQL常量。
  • 用String.format()替换Sql语句创建中的任何字符串连接。
  • 对于任何String.format命令,您必须跳出任何现有的%符号。这些符号通常用于LIKE操作。

我如何才能将这个SQL查询到公共静态字符串MY_QUERY',这样它不会向前引用和“比赛”和“useFor”变量就可以解决。我将使用MY_QUERY执行的操作是从JUnit Test访问它,然后对源数据库和目标数据库执行查询,以确保查询在两个数据库上执行所需的查询以进行数据迁移。

package artemispm.autocalc; 

import java.sql.*; 
import java.util.*; 
import a7.unittests.dao.UnitTestHelper; 
import artemispm.serverutil.*; 
import artemispm.trdo.*; 
import artemispm.parser.*; 

public abstract class TRBaseScoreCalculator implements ExpressionParserLookup { 

/*****THIS IS THE NEW QUERY THAT WILL BE ACCESSED FROM JUNIT TEST****/ 

public static String MY_QUERY = 

public Connection    m_con; 
protected String    m_characName  = ""; 

public boolean isThisCharacInUse(Connection con, String characName,String useFor) 
throws SQLException, TRException { 
boolean result;   
String match = "[" + TRBaseSql.rewrapQuotes(characName) + "]"; 

if(TRBaseSql.getDatabaseType(con) == TRBaseSql.DBTYPESQLSERVER) { 
    match = "[[]" + TRBaseSql.rewrapQuotes(characName) + "]"; 
} 

TRSystemSQL sql = new TRSystemSQL(); 
TRSystem sys=sql.getSystem(con); 
result = ( sys.getScoreCalculation() != null 
      && sys.getScoreCalculation().indexOf(match) >= 0 ); 
if (result) return(result); 
else { 

    int count; 

    /*****THIS IS THE PLACE I NEED HELP AT 12/5/2012 ******/ 
/*I NEED TO SOMEHOW MOVE THE BELOW STATEMENT USING THE SPECS INTO MY_QUERY**/ 
/**"select count(userfieldid) from tr_userfield where calcexpression like '%" + match + "%'and usefor like '%" + useFor +"%'"***/ 

    count = sql.executeGetInt(con, "select count(userfieldid) from tr_userfield where calcexpression like '%" + match + "%'and usefor like '%" + useFor +"%'" , null); 

    if (count > 0) return true; 
    count = sql.executeGetInt(con, 
      "select count(characid) from tr_charac where calcexpression like '%" + match + "%'and usefor like '%" + useFor +"%'" , null); 
    return (count > 0); 
    } 
} 
} 

回答

1

你可以欺骗并执行以下操作:

恒:

private static final String FORMAT = "select count(userfieldid) " + 
    "from tr_userfield " + 
    "where calcexpression like '%c%s%c' and usefor like '%c%s%c'"; 

private static final char WILDCARD = '%'; 

创建查询:

String calcExpression = "a"; 
String useFor = "b"; 

String query = String.format(FORMAT, WILDCARD, calcExpression, WILDCARD, 
    WILDCARD, useFor, WILDCARD); 
System.out.println(query); 

它给你:

来自tr_userfield的select count(userfieldid),其中calcexpression类似于'%a%'并且用于like'%b%'