Sunday, 22 March 2020

Jdbc: Retrieve column names from ResultSet

‘ResultSetMetaData’ class is used to get the column names.

Example
query = "SELECT id, firstName, lastName FROM employee";
ResultSet resultSet = stmt.executeQuery(query);
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
String columnName1 = resultSetMetaData.getColumnName(1);
String columnName2 = resultSetMetaData.getColumnName(2);
String columnName3 = resultSetMetaData.getColumnName(3);

App.java
package com.sample.app;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class App {

 // Initialize url username and password
 private static final String URL = "jdbc:mysql://localhost/sample";
 private static final String USERNAME = "krishna";
 private static final String PASSWORD = "krishna";

 public static void main(String args[]) throws SQLException, ClassNotFoundException {

  /* Open connection to database */
  System.out.println("Connecting to database");

  Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);

  /* Create table employee */
  String query = "CREATE TABLE employee (id int, firstName varchar(30), lastName varchar(30), PRIMARY KEY(id))";
  Statement stmt = conn.createStatement();
  stmt.execute(query);

  /* Insert data to employee table */
  query = "INSERT INTO employee values(1, \"Krishna\",  \"Gurram\")";
  stmt.execute(query);
  query = "INSERT INTO employee values(2, \"Gopi\",  \"Battu\")";
  stmt.execute(query);

  query = "SELECT id, firstName, lastName FROM employee";
  ResultSet resultSet = stmt.executeQuery(query);
  ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
  String columnName1 = resultSetMetaData.getColumnName(1);
  String columnName2 = resultSetMetaData.getColumnName(2);
  String columnName3 = resultSetMetaData.getColumnName(3);
  
  System.out.println(columnName1 + " " + columnName2 + " " + columnName3);

  while (resultSet.next()) {
   int id = resultSet.getInt("id");
   String firstName = resultSet.getString("firstName");
   String lastName = resultSet.getString("lastName");
   System.out.println(id + " " + firstName + " " + lastName);
  }

  System.out.println("Dropping the table employee");

  String sql = "DROP TABLE employee";

  stmt.executeUpdate(sql);

  resultSet.close();
  conn.close();
  conn.close();
 }
}

Output

Connecting to database
id firstName lastName
1 Krishna Gurram
2 Gopi Battu
Dropping the table employee

Previous                                                    Next                                                    Home

No comments:

Post a Comment