1. 程式人生 > >SQL解析,已知查詢字串,表字符串,求表名及其對應欄位

SQL解析,已知查詢字串,表字符串,求表名及其對應欄位

/**
         * select s.id sid , g.id , s.name from student a , grade g where s.id = g.sid
         * 暫未考慮巢狀查詢
         * 
         */
   
//    String[] tables = new String[]{"student"};
//    String[] zds = new String[]{"id sid","sex","name"};
    String[] tables = new String[]{"student s","grade g"};
    String[] zds = new String[]{"s.id sid","g.id","s.name"};
    //解析結果
    Map<String , List<String>> result = new HashMap<>();
    //查詢欄位顯示(有別名顯示別名)
    List<String> showZDs = new ArrayList<>();


    for (String table : tables) {
    List<String> showZD = new ArrayList<>();
    List<String> tableZD = new ArrayList<>();
table = table.trim();
try {
//獲取表別名
String tableF = table.substring(table.lastIndexOf(" ")+1);
table = table.substring(0, table.indexOf(" "));

for (String string : zds) {
string = string.trim();
if(string.lastIndexOf(" ")==-1){
//顯示欄位無別名
showZD.add(string.substring(string.indexOf(".")+1));
//獲取欄位表別名
String zdF = string.substring(0, string.indexOf("."));
if(zdF.equals(tableF)){
tableZD.add(string.substring(string.indexOf(".")+1));
}
}else{
//顯示欄位有別名
showZD.add(string.substring(string.lastIndexOf(" ")+1));
//與表字段一致
String zdF = string.substring(0, string.indexOf("."));
if(zdF.equals(tableF)){
tableZD.add(string.substring(string.indexOf(".")+1, string.indexOf(" ")));
}
}
}
result.put(table, tableZD);
} catch (Exception e) {
//表無別名  單表
for (String string : zds) {
string = string.trim();
if(string.lastIndexOf(" ")==-1){
//顯示欄位無別名
showZD.add(string);
tableZD.add(string);
}else{
//顯示欄位有別名
showZD.add(string.substring(string.lastIndexOf(" ")+1));
//獲取表字段
tableZD.add(string.substring(0, string.indexOf(" ")));
}
}
result.put(table, tableZD);
}
showZDs=showZD;
}
   
    System.out.println(result.entrySet());

    System.out.println(showZDs);

//執行結果

[student=[id, name], grade=[id]]
[sid, id, name]