简体   繁体   中英

SQL in java - get the number of columns

I've been using sql with java for a while now. The code typically goes like this -

conn = DriverManager.getConnection(url, user, pwd); 
PreparedStatement pstat = conn.prepareStatement("select * from table");
ResultSet rs = pstat.executeQuery();
while(rs.next()){
  System.out.print(rs.getString(1) + "," + rs.getString(2) + "...");
}

I haven't been able to figure out how to get the total count of columns. I never needed it because I had access to DBVisualizer and knew the exact number of columns from there. However, I now want to write a java program that prints out all the results of the query and so, need the number of columns so I can print all of them in the while loop instead of guessing. Whats the best way to do this?

Use ResultSetMetaData.getColumnCount() - Returns the number of columns in this ResultSet object.

ResultSet rs = pstat.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();

See ResultSetMetaData

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