ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// The column count starts from 1
for (int i = 1; i <= columnCount; i++ ) {
String name = rsmd.getColumnName(i);
// Do stuff with name
}
使用MetaData of a result set to fetch the exact column count
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
boolean b = rsmd.isSearchable(1);
ResultSetMetaData meta = resultset.getMetaData(); // for a valid resultset object after executing query
Integer columncount = meta.getColumnCount();
int count = 1 ; // start counting from 1 always
String[] columnNames = null;
while(columncount <=count) {
columnNames [i] = meta.getColumnName(i);
}
System.out.println (columnNames.size() ); //see the list and bind it to TableModel object. the to your jtbale.setModel(your_table_model);
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
Vector<Vector<String>>tableVector = new Vector<Vector<String>>();
boolean isTableEmpty = true;
int col = 0;
while(rs.next())
{
isTableEmpty = false; //set to false since rs.next has data: this means the table is not empty
if(col != columnCount)
{
for(int x = 1;x <= columnCount;x++){
Vector<String> tFields = new Vector<String>();
tFields.add(rsmd.getColumnName(x).toString());
tableVector.add(tFields);
}
col = columnCount;
}
}
//if table is empty then get column names only
if(isTableEmpty){
for(int x=1;x<=colCount;x++){
Vector<String> tFields = new Vector<String>();
tFields.add(rsmd.getColumnName(x).toString());
tableVector.add(tFields);
}
}
rs.close();
stmt.close();
return tableVector;
PreparedStatement stmt = connection.prepareStatement("SHOW COLUMNS FROM `yourTable`");
ResultSet set = stmt.executeQuery();
//store all of the columns names
List<String> names = new ArrayList<>();
while (set.next()) { names.add(set.getString("Field")); }
jdbcTemplate.query("select * from books", new RowCallbackHandler() {
public void processRow(ResultSet resultSet) throws SQLException {
ResultSetMetaData rsmd = resultSet.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++ ) {
String name = rsmd.getColumnName(i);
// Do stuff with name
}
}
});