How to Get Column Names from Database Table with Java
Let’s say you have a table in a SQL database and you want to discover the names of the columns from Java. One way to do this that is pretty straightforward is with the following code.
import java.sql.*; ... public ArrayList<String> GetColumnNames(String tableName) throws Exception { DatabaseMetaData meta = _conn.getMetaData(); ResultSet rsColumns = meta.getColumns(null, null, tableName, null); ArrayList<String> columnNames = new ArrayList<String>(); while (rsColumns.next()) columnNames.add(rsColumns.getString("COLUMN_NAME")); rsColumns.close(); return columnNames; }
I have only tested this with a SQLite database, but I can’t think of any reason it wouldn’t work with other database systems such as Oracle, mySQL, etc.