Frage

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?

War es hilfreich?

Lösung

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top