如何解析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;
答案 0 :(得分: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());
}
}
}