SQL查询将作为字符串传递给我的方法,如果查询是例如,我如何检索查询中的列名称?
Select name, dob, age, gender from table1; or
Select uname AS name, hgt AS height, wgt AS weight from table1;
我想在数组或列表中获取列名。
答案 0 :(得分:1)
你试过吗
ResultSetMetaData rsmd = rs.getMetaData();
String name = rsmd.getColumnName(1);
答案 1 :(得分:1)
虽然有点令人费解,但这适用于问题中列出的查询:
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(",");
答案 2 :(得分:0)
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));
}
}
输出
Orignal empid
Alias eid
Orignal ename
别名
Orignal deptid
Alias department_id