1

如何解析 SQL 查询(字符串格式)并提取 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";

我想出了以下代码,如果值包含逗号,则该代码不起作用。

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;
4

1 回答 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());
        }
    }
}
于 2013-08-15T09:52:16.563 回答