generate Count SQL - Java java.lang

Java examples for java.lang:String SQL

Description

generate Count SQL

Demo Code

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main{
    public static void main(String[] argv){
        String ql = "java2s.com";
        System.out.println(generateCountQl(ql));
    }/*from ww w  . jav  a 2  s. c  o  m*/
    public static String generateCountQl(String ql) throws Exception {
        StringBuilder countQl = new StringBuilder(ql.trim());
        countQl.trimToSize();

        // Find the index of "from"
        int indexOfFrom = 0;
        int index = 0;
        indexOfFrom = ql.toLowerCase().indexOf("from");
        index = indexOfFrom;
        if (index < 0)
            throw new Exception(
                    "Illegal JPQL statment, no 'FROM' was found.");

        // TODO to be continue
        // Substring after from
        String subString = countQl.substring(index + 4).trim();

        index = subString.indexOf(" ");
        subString = subString.substring(index, subString.length()).trim();
        index = subString.indexOf(" ");
        if (index > 0)
            subString = subString.substring(0, index);

        countQl.delete(6, indexOfFrom);

        countQl.insert(6, " COUNT(" + subString + ") ");

        return countQl.toString();
    }
}

Related Tutorials