List All Column Names of Table using Java
We can list all column names of table using java.sql.DatabaseMetaData.getColumns() method. The getColumn method accepts String catalog, String schemaPattern, String tableNamePattern and String columnNamePattern parametres. It retrieves a description of table columns available in the specified catalog. The method return ResultSet where each row is a column description.
Example to list all column names of table using java:-
import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; public class IsDbExist { public static void main(String[] args){ Connection con = null; ResultSet rs = null; String url = "jdbc:mysql://localhost:3306/mysql"; String user = "root"; String password = ""; try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url, user, password); if(con != null){ System.out.println("list all column names of table using java"); DatabaseMetaData dbmd = con.getMetaData(); rs = dbmd.getColumns(null, null, "user", "%"); while(rs.next()){ String tablelist = rs.getString("COLUMN_NAME"); System.out.println(tablelist); } } else{ System.out.println("unable to create database connection"); } } catch(Exception ex){ ex.printStackTrace(); } finally{ if( rs != null){ try{ rs.close(); } catch(SQLException ex){ ex.printStackTrace(); } } if( con != null){ try{ con.close(); } catch(SQLException ex){ ex.printStackTrace(); } } } } }
output:-
list all column names of table using java Host User Password Select_priv Insert_priv Update_priv Delete_priv Create_priv Drop_priv Reload_priv Shutdown_priv Process_priv File_priv Grant_priv References_priv Index_priv Alter_priv Show_db_priv Super_priv Create_tmp_table_priv Lock_tables_priv Execute_priv Repl_slave_priv Repl_client_priv Create_view_priv Show_view_priv Create_routine_priv Alter_routine_priv Create_user_priv Event_priv Trigger_priv Create_tablespace_priv ssl_type ssl_cipher x509_issuer x509_subject max_questions max_updates max_connections max_user_connections plugin authentication_string password_expired
Description of parameters available in getColumns() method:-
catalog:- is the name of catalog. it must match with the catalog name stored in the database, the catalog can be null, means should not be used to narrow the search or “” means retrieves those without a catalog.
schemaPattern:- is a schema name pattern. it must match with the schema name stored in the database, schemaPattern can be “” means retrieves those without a schema or null that means schema name should not be used to narrow the search.
tableNamePattern:- is a table name pattern. it must match with the table name stored in the database.
columnNamePattern:- is a column name pattern. it must match with the column name stored in the database.