简体   繁体   English

如何从SQL查询中提取列名作为字符串SQL查询作为String传递

[英]How to extract column names from SQL Query as String SQL query is passed as a String

An SQL Query will be passed to my Method as a String, How can i retrieve the Column names in the query, if the query is eg SQL查询将作为字符串传递给我的方法,如果查询是例如,我如何检索查询中的列名称

Select name, dob, age, gender from table1; or 
Select uname AS name, hgt AS height, wgt AS weight from table1;

I want to get the Column names in an Array or List. 我想在数组或列表中获取列名称。

have you tried 你有没有尝试过

ResultSetMetaData rsmd = rs.getMetaData();
String name = rsmd.getColumnName(1);

Though somewhat convoluted this works for both the queries listed in the question : 虽然有点令人费解,但这适用于问题中列出的查询:

String query = "Select uname AS name, hgt AS height, wgt AS weight from table1";
Pattern p = Pattern.compile("\\s*\\w+,");Pattern p1 = Pattern.compile("\\s+\\w+\\s+from");
Matcher m = p.matcher(query);Matcher m1=p1.matcher(query);
String colsOnly="";
while(m.find()){colsOnly+=(m.group().trim());}
while(m1.find()){colsOnly+=(m1.group().substring(0,m1.group().length()-4).trim());}
String[] cols = colsOnly.split(",");
    String str = "select dept,empid as eid , ename as name,deptname,deptid as department_id from emp";

    String[] arr = str.split("as");
    StringTokenizer str1 = new StringTokenizer(str, " ,");
    ArrayList<String> arrStr = new ArrayList<>();
    while (str1.hasMoreTokens())
    {
        String strT = str1.nextToken().toString();          
        arrStr.add(strT);
    }       
    for (int i = 0; i < arrStr.size(); i++)
    {
        if (arrStr.get(i).equals("as"))
        {
            System.out.println("Orignal\t" + arrStr.get(i - 1));
            System.out.println("Alias\t" + arrStr.get(i + 1));
        }
    }

Output 产量

Orignal empid Orignal empid

Alias eid 别名开斋节

Orignal ename Orignal ename

Alias name 别名

Orignal deptid Orignal deptid

Alias department_id 别名department_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM