In this example of getting the columns names we need to have connection with the database and then after we will get metadata of this table and find the columns name within the metadata.
Java program to get column names of a table
In this example of getting the columns names we need to have connection with the database and then after we will get metadata of this table and find the columns name within the metadata.
In our example program we have created a database connection with the data table within the MySQL database. The data table view is as follows:
To have metadata related manipulation we need to have
an object of ResultSetMetaData and thereafter we can do the manipulation
on the table related information.
ResultSetMetaData rsmd = rs.getMetaData();
int NumOfCol = rsmd.getColumnCount();
Above lines of code creates an object of ResultSetMetaData and we can get the number of columns with the use of getColumnCount() methods. Now we can get the column names with the index value by the method getColumnName().Here is the example code of GetColumnName.java as follows:
GetColumnName.java
import java.sql.*; public class GetColumnName { public static void main(String[] args) throws Exception { String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/"; String username = "root"; String password = "root"; String dbName= "any"; Class.forName(driver); Connection conn = DriverManager.getConnection(url+dbName, username, password); System.out.println("Connected"); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM webpages"); ResultSetMetaData rsmd = rs.getMetaData(); int NumOfCol = rsmd.getColumnCount(); for(int i=1;i<=NumOfCol;i++) { System.out.println("Name of ["+i+"] Column="+rsmd.getColumnName(i)); } st.close(); conn.close(); } } |
Output:
C:\javaexamples>javac GetColumnName.java C:\javaexamples>java GetColumnName Connected Name of [1] Column=id Name of [2] Column=title Name of [3] Column=url Name of [4] Column=pageContent |