Jdbc Get Column Names
The JDBC Get Column Names return you the property of the retrieved Column like its field name and data type using meta Data.
Understand with Example
The Tutorial illustrates an example from JDBC Get Column Names The Program describe you a code that explain you the column property like field name, data type. We define a class JdbcGetColumn Names, The main method include a list of method to be carried out in order to get Column Properties -
Importing a package java.sql.* enables you a network interface to communicate between front end and backend. Inside the main method we load a driver by calling a class.forName ( ) and accept a jdbc.driver as argument.The DriverManager.getConnection( ) return you a connection object that help in implementing url and database.con.create Statement ( ) return you statement object. This object is used to send and execute sql queries in the backend. The statement object calls executeQuery ( )method, which return you a result set. The result set include a record set retrieved from table. The result set call the list of following method to get the column property information in the table.
Methods | Descriptions |
get Metadate( ) | This method return you an object that is needed to get the information about the type and properties of the column |
getColumnCount ( ) | This method is used to count the number of field in the table |
getTableName ( ) | This return you the name of the table |
getColumnName( ) | This return you the name of column |
Finally the println print the Table name, field name and data type using metadata.
In case there exists an exception in the try block, the subsequent catch block caught and handle the exception
JdbcGetColumnNames.java
import java.sql.*; public class JdbcGetColumnNames { public static void main(String args[]) { Connection con = null; Statement st = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/komal", "root", "root"); st = con.createStatement(); String sql = "select * from person"; rs = st.executeQuery(sql); ResultSetMetaData metaData = rs.getMetaData(); int rowCount = metaData.getColumnCount(); System.out.println("Table Name : " + metaData.getTableName(2)); System.out.println("Field \tDataType"); for (int i = 0; i < rowCount; i++) { System.out.print(metaData.getColumnName(i + 1) + " \t"); System.out.println(metaData.getColumnTypeName(i + 1)); } } catch (Exception e) { System.out.println(e); } } } |
Output
Table Name : person Field DataType id VARCHAR cname VARCHAR dob DATE |