0

我正在尝试使用从视图(JSP)到控制器的最终用户的选定字段进行查询,但我不知道如何。

例如,我有这个参数来自视图(JSP)

IDUSER,>,2,OR,USERNAME,=,'KURT'

所以,我想要这样的东西,

SELECT IDUSER, USERNAME FROM TABLE_NAME WHERE IDUSER > 2 OR USERNAME = 'KURT'

但我有下一个结果

SELECT null FROM TABLE_NAME WHERE IDUSER > 2 OR USERNAME = 'KURT'

我正在用StringTokenizer类解析字符串,其中查询是:String query = request.getParameter("data");而数据是IDUSER,>,2,OR,USERNAME,=,'KURT'

StringTokenizer field = new StringTokenizer(query, ",");
nFields = field.countTokens();
System.out.println("nFields: " + nFields);
String[] fields = new String[nFields];
for(int i = 0; i < fields.length; i++) {
    while(field.hasMoreTokens()) {
         fields[i] = field.nextToken();
    }
    System.out.println("fields[i]: " + fields[i]);
    myQuery = "SELECT " + fields[i] + " FROM "+tableName+ " WHERE ";
    System.out.println("myQuery 1: " + myQuery);
}
StringTokenizer token= new StringTokenizer(query, "|,");
while(token.hasMoreTokens()) {
     myQuery = myQuery + token.nextToken() + " ";
}
System.out.println("QUERY RESOLVED: " + myQuery);

请帮我

4

3 回答 3

1

这是对查询进行细微调整后的解决方案(重新定义分隔符)

public static void main(String[] args) {
        // Redefine the separators as single , separators is difficult to process
        //You would need to define possible operators like this (#OR# , #AND# ) ,surrounded by special characters to identify.
        String query ="IDUSER_>_2#OR#USERNAME_=_'KURT'";
        String tableName="TESTTABLE";
        String operator=null;
        //you can choose operator conditionally
        if(query.contains("#OR#")) operator="#OR#";
//      if(query.contains("#AND#")) operator="#AND#";
        //Used split instead of Tokenizer.
        String cols[]= query.split(operator);
        String myQuery = "SELECT ";
        String select="";
        for(String col:cols){
            if(!select.isEmpty()){
                select+=" , ";
            }
            // Only the first element is retrieved (for select)
            select+=col.split("_")[0];
        }
        myQuery+=select+" FROM "+tableName+ " WHERE ";
        // Removes all special charecters (like,  # and _ with white space)
        String subQuery = query.replaceAll("#", " ");
        subQuery=subQuery.replaceAll("_", "");
        myQuery+=subQuery;
        System.out.println("QUERY RESOLVED: " + myQuery);

    }

注意: ',' 替换为 '_' 并且操作符被 '#' 包围

干杯!!

于 2012-09-21T06:39:02.290 回答
0

我认为问题在于您的 while 循环中的这一行:

myQuery = "SELECT " + fields[i] + " FROM "+tableName+ " WHERE ";

myQuery这将在 while 循环执行时不断改变 的值。

也许您需要将其替换为:

myQuery = "SELECT " + fields[0] + " FROM "+tableName+ " WHERE ";
break;

我假设您的选择标准是您认为参数中的第一个字段。

于 2012-09-20T07:45:23.457 回答
0

不知道IDPERFIL从哪里来。另外,我不喜欢这样:

while(field.hasMoreTokens()) {
     fields[i] = field.nextToken();
}

这会将标记器迭代到最后,并在最后一个元素处停止。我敢肯定你不想要这个。解决这个问题,告诉 IDPERFIL 来自哪里,然后,也许,你会自己理解答案。否则,我会尽力提供进一步的帮助。

于 2012-09-20T07:45:33.647 回答