Reputation: 11053
How can I get all columns' names from an Oracle table using Java? Is there a way to get them from DatabaseMetaData object?
DatabaseMetaData myDatabaseMetaData = myConnection.getMetaData();
...
I know I can get them using a select statement:
Select COLUMN_NAME from user_tab_columns where table_name='MYTABLE'
If it is possible to get them from DatabaseMetaData object, what is the difference between the two methods?
EDIT: Posting working code (thanks for your answers)
public ArrayList<String> getAllFields(String tableName) {
ArrayList<String> allFields = new ArrayList<String>();
try {
DatabaseMetaData myDatabaseMetaData = myConnection.getMetaData();
ResultSet columnsResultSet = myDatabaseMetaData.getColumns(null, null, tableName, null);
while (columnsResultSet.next()) { allFields.add(columnsResultSet.getString("COLUMN_NAME")); }
} catch (SQLException ex) {
Exceptions.printStackTrace(ex);
}
return allFields;
}
Upvotes: 1
Views: 12005
Reputation: 24630
DatabaseMetaData is an interface, so it depends all on the JDBC driver implementation. Be shure to use the best and last published one.
Upvotes: 1
Reputation: 749
DatabaseMetaData#getColumns(String, String, String, String)
Your direct SQL call will only work in Oracle, while the DatabaseMetaData method should be database independent.
Upvotes: 2
Reputation:
You are looking for DatabaseMetaData.getColumns()
Well the difference between your SQL and the JDBC API is, that the API call is supposed work on all DBMS, whereas the SQL will only work on Oracle.
Upvotes: 6