1

How I can parse an SQL Query (in string format) and extract the Column Names and the values in a HashMap ?

In:
INSERT INTO CUSTOMERS (ID,NAME,AGE)
VALUES (4, 'Chaitali', 25);
Out:
key "ID", value "4";
key "NAME", value "Chaitali";
key "AGE", value "25";

I came up with the following code, which does not work if values contain commas.

HashMap<String, String> map = new HashMap<String, String>();    

int startValues = sql.lastIndexOf(" (");
int endValues = sql.length();
String valuesSubstring = sql.substring(startValues +2, endValues-1);
String [] valuesMassive = valuesSubstring.split(",");

int startKeys = sql.indexOf("(");
int endKeys = sql.indexOf(")");
String keysSubstring = sql.substring(startKeys+1, endKeys);
String [] keysMassive = keysSubstring.split(",");

for(int i = 0; i < keysMassive.length; i++) {
    map.put(keysMassive[i].trim(), valuesMassive[i]);
}

return map;
0

1 Answer 1

1
public class SqlSplit {

    public static void main(String[] args) {
        String query = "INSERT INTO CUSTOMERS (ID,NAME,AGE) VALUES (4, 'Chaitali', 25);";
        Pattern pattern = Pattern.compile("\\((.*?)\\)",Pattern.DOTALL);

        Matcher matcher = pattern.matcher(query);
        List<String[]> tokens = new ArrayList<String[]>();
        while(matcher.find()){
            tokens.add(matcher.group().replace("(","").replace(")","").split(","));     
        }

        Map<String,String> map = new HashMap<String,String>();
        if(tokens.size() == 2 && tokens.get(0).length == tokens.get(1).length){
            for(int x = 0; x < tokens.get(0).length; x++){
                map.put(tokens.get(0)[x], tokens.get(1)[x].replace("'", ""));
            }
        }

        for(Entry<String,String> entry: map.entrySet()){
            System.out.println("KEY:" + entry.getKey());
            System.out.println("VALUE:" + entry.getValue());
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.