简体   繁体   中英

How to get column count in SQL before executing the query? i.e. way other than ResultSetMetaData

I have a sql query. Because of too many BO's are involved, it's forming very big query containing more than 1000 columns. So I need some way with which I can find column count before hand and then apply some logic to handle 1000 column error.

May be parsing a query to get column count would help. But not getting how to implement it.

Note: tried below code already, it's giving me result, but i dont want to execute query, that's costly.

PreparedStatement pstmt;
    try {
        pstmt = getConnection().prepareStatement(sql);
        ResultSetMetaData meta = pstmt.getMetaData();
        System.out.println(meta.getColumnCount());

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

If it is a plain old select query like :

select col1,col2 as xyz, col3,col4... from ... where ...

you can do something like this:

String select="select";//"SELECT" if yours is in caps
String from="from";//"FROM" if yours is in caps
String cols = sql.substring(sql.indexOf(select)+select.length(), sql.indexOf(from)); 
int colCount = cols.split(",").length;

If your query contains functions like fn(col,'blah blah') you need to write some extra code to ID such functions and process things appropriately.

I guess your SQL query using lot of wildcards after SELECT statement right? If no wildcard used, you can parse SQL query part between SELECT and FROM to get column numbers.I feel some disturbance in the force if i hear you have such big results of unknown attributes. If we can say that SQL table is data source, we can say that query result is data source too. In case of SQL table we have defined very specifically what columns(attributes) it contain. If u create SQL query without specification of columns you have data source of unknown entity. Are you trying to create some BI system? If yes you should consider to get metadata of table and create specific query based on this informations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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