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 に答える