Skip to content
Related Articles

Related Articles

Java Program to Use Methods of Column to Get Column Name in JDBC
  • Last Updated : 15 Dec, 2020

Java Database Connectivity or JDBC is a Java API (application programming interface) used to perform database operations through Java application. It allows the execution of SQL commands for the creation of tables and data manipulation through Java application. Java supports java.sql package which contains inbuilt methods for accessing and processing data stored in a database. The methods in java.sql throw SQL exceptions hence the code block must be either placed within a try block and let the catch block handle exceptions if any else add throws clause to the main method. 

Procedure:

  1. The forName() is a static method of class which is used to load the driver.
  2. Next the connection to the database is established using the getConnection() method of DriverManager class. The getConnection() accepts the URLs, username and password to establish a connection. The methods defined in the Statement interface is used to interact with the database.
    • First, the table is created and then records are inserted into the table.
    • The sql commands are batched together using addBatch() and executed all at once using executeBatch() method.
    • The records in the table are fetched into the ResultSet.
    • The getMetaData() method of ResultSet is used to get the metadata of the records fetched into the ResultSet.
    • The getColumnCount() and getColumnName() methods of ResultSetMetaData interface is used to get the number of columns and name of each column in the table.

Example 1:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to Use Methods of Column
// to get column name in JDBC
  
// Step 1: Importing DB files
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
  
// Class to get columns
public class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        try {
  
            // Step 2: Lodaing and registering drivers
  
            // Loading driver class
            // using forName() method
            Class.forName("oracle.jdbc.OracleDriver");
  
            // Step 3: Establishing te connection
  
            Connection con = DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:xe",
                "username", "password");
            Statement s = con.createStatement();
  
            // Step 4: Create a statement
            String sql1
                = "CREATE TABLE ACADEMY(COURSE_ID VARCHAR2(20) PRIMARY KEY, COURSE_NAME VARCHAR2(20),MENTOR VARCHAR2(20),COURSE_FEE NUMBER)";
  
            // Step 5: Process the querry
            // Inserting records in the table
            String sql2
                = "INSERT INTO ACADEMY VALUES('C101','MATH','ROBERT',5000)";
            String sql3
                = "INSERT INTO ACADEMY VALUES('C102','PHYSICS','JANE',8000)";
            String sql4
                = "INSERT INTO ACADEMY VALUES('C103','HISTORY','ADAM',6000)";
            String sql5
                = "INSERT INTO ACADEMY VALUES('C104','BIOLOGY','MARIE',5000)";
            String sql6
                = "INSERT INTO ACADEMY VALUES('C105','ENGLISH','ALBERT',3000)";
            s.addBatch(sql1);
            s.addBatch(sql2);
            s.addBatch(sql3);
            s.addBatch(sql4);
            s.addBatch(sql5);
            s.addBatch(sql6);
  
            // Step 6: Execute the statements
            // executing the sql commands
            s.executeBatch();
  
            // Obtaining the resultset
            ResultSet rs
                = s.executeQuery("SELECT * FROM ACADEMY");
  
            while (rs.next()) {
  
                System.out.println(
                    rs.getString(1) + "\t\t"
                    + rs.getString(2) + "\t\t"
                    + rs.getString(3) + "\t\t"
                    + rs.getString(4));
            }
  
            // Retrieving the ResultSetMetadata object
            ResultSetMetaData rsMetaData = rs.getMetaData();
            System.out.println(
                "List of column names in the current table: ");
  
            // Retrieving the list of column names
            int count = rsMetaData.getColumnCount();
  
            for (int i = 1; i& lt; = count; i++) {
                System.out.print(rsMetaData.getColumnName(i)
                                 + "\t");
            }
  
            // Step 7: Close the connection
            con.commit();
            con.close();
        }
  
        // Catch block to handle exceptions
        catch (Exception e) {
  
            // Print the exception
            System.out.println(e);
        }
    }
}

chevron_right


Output:



Example 2:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to Use Methods of Column
// to get column name in JDBC
  
// Step 1: Importing DB files
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
  
// Class
public class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
  
        // Try block to check if exception occurs
        try {
  
            // Step 2: Loading and registering drivers
  
            // Loading driver class
            // using forName() method
            Class.forName("oracle.jdbc.OracleDriver");
  
            // Step 3: Establish a connection
  
            // Create connection object
            Connection con = DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:xe",
                "cse", "cse");
            Statement s = con.createStatement();
  
            // Step 4: Create a starement/s
            // create table
            String sql1
                = "CREATE TABLE STUDENT(STUDENTID VARCHAR2(20) PRIMARY KEY, NAME VARCHAR2(20), DEPARTMENT VARCHAR2(10))";
            // insert records in the table
            String sql2
                = "INSERT INTO STUDENT VALUES('S001','JOE','CSE')";
            String sql3
                = "INSERT INTO STUDENT VALUES('S002','BECK','IT')";
            String sql4
                = "INSERT INTO STUDENT VALUES('S003','KANE','ECE')";
            String sql5
                = "INSERT INTO STUDENT VALUES('S004','FALLON','CSE')";
            String sql6
                = "INSERT INTO STUDENT VALUES('S005','LIAM','CSE')";
  
            // Step 5: Execute the querry
            s.addBatch(sql1);
            s.addBatch(sql2);
            s.addBatch(sql3);
            s.addBatch(sql4);
            s.addBatch(sql5);
            s.addBatch(sql6);
  
            // Executing the sql commands
            s.executeBatch();
  
            // Obtaining the resultset
  
            ResultSet rs
                = s.executeQuery("SELECT * FROM STUDENT");
  
            // Retrieving the ResultSetMetadata object
            ResultSetMetaData rsMetaData = rs.getMetaData();
  
            // Retrieving the list of column names
            int count = rsMetaData.getColumnCount();
  
            // Step 6: Process the statements
            for (int i = 1; i <= count; i++) {
                System.out.print(rsMetaData.getColumnName(i)
                                 + "\t");
            }
  
            System.out.println(
                "\n----------------------------------------------------------------");
            while (rs.next()) {
                System.out.println(rs.getString(1) + "\t\t"
                                   + rs.getString(2) + "\t"
                                   + rs.getString(3));
            }
  
            // Step 7: Close the connection
            con.commit();
            con.close();
        }
  
        // Catch block to handle if exception occurs
        catch (Exception e) {
  
            // Print the exception
            System.out.println(e);
        }
    }
}

chevron_right


Output


Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :