Getting Column Names from a database table in Java
Here we are providing you an example with code that retrieves all columns name in a specific database table. Sometimes, you need to know the number of columns and the names of the columns of the table, so you can retrieve it with the help of this example. See detail information given below:
Description of program:
Create a class ColumnName. The name of the class should be such that the other person can easily understand what this program is going to do. Strictly follow the naming conventions of java. Now declare a static method inside which creates the connection with MySQL database through the JDBC driver. After establishing the connection then you get all columns name and number of columns of specified table with the help of some APIs and methods.
Description of code:
ResultSetMetaData:
This is an interface of java.sql package that can be used for
getting information about types and properties of columns in a ResultSet
object.
getColumnCount():
Above method retrieves number of columns (integer types data) in the ResultSet
object.
getColumnName(int column):
This method returns columns name (string type data) from ResultSetMetaData
object and takes integer type value.
Here is the code of program:
import java.sql.*;
|
Output of program:
C:\vinod\jdbc\jdbc-mysql>javac ColumnName.java C:\vinod\jdbc\jdbc-mysql>java ColumnName Getting Column Names Example! Number of Column : 2 Columns Name: Emp_code Emp_name |