Friday, June 29, 2018

A great JDBC API the ResultSetMetaData interface

### ResultSetMetaData ###

It is an interface, and its is a part of JDBC API. 
This interface is one of the most useful interface of JDBC API.

# Objective # 


By using this interface we can provide a Metadata about ResultSet. 
Metadata means the data about data.

# For example #

ResultSet keeps the data of table whereas the ResultSetMeta keeps the information about ResultSet.

Real life example: If Person is a ResultSet then the biography of Person is a ResultSetMeta.


How to get the object of ResultSetMeta:


the syntax => ResultSetMeta refvar = objectOfResultSet.getMetaData();


here, getMetaData() is a method of ResultSet, that returns object of ResultSetMeta.


# Methods of ResultSetMeta #


1. int getColumnCount() -> This method will return number of columns available inside ResultSet.


2. String getColumnName(int indexOfColumn) -> This method will return the name of column available at given index


3. String getColumnTypeName(int indexOfColumn) -> This method will return the type of column available at given index


Note: in method 2 and 3 the indexOfColumn must be >= 1 and < number of columns in ResultSet. 




# First program to show the application of ResultSetMetaData #

note: save this code inside FirstApplicationOfResultSetMetaData.java file

import java.sql.*;
import java.util.Scanner;
public class FirstApplicationOfResultSetMetaData
{
public static void main(String[] args)
{
try
{
// lets create object of sccaner class to get input from keyboard
Scanner sc = new Scanner(System.in);

System.out.print("Enter the name of database: ");
  // get name of database from the keyboard
String dbName = sc.nextLine();

System.out.print("Enter the name of the table: ");
// get name of table from the keyboard
  String tableName = sc.nextLine();

// lets load the driver class for MySQL server database
Class.forName("com.mysql.jdbc.Driver");

// lets get object of connection to communicate with database
// note: co is the object name of connection
Connection co = DriverManager.getConnection
("jdbc:mysql://localhost:3306/"+dbName, "root","root");

// lets get object of statement to make a dialog with database
// note: st is the object name of statement
Statement st = co.createStatement();

// lets execute the select query
// note: rs is the object of resultset, which will keep the data of table
// note: here i have prefixed the name of database than dot (bole toh .)
// than the name of table
ResultSet rs = st.executeQuery("select * from "+dbName+"."+tableName);

// lets get object of resultsetmetadata to know about resultset
// note: rsmd is the object of resultsetmetadata
ResultSetMetaData rsmd = rs.getMetaData();

// lets get number of columns inside the resultset
int columns = rsmd.getColumnCount();

System.out.println("# No of columns inside ResultSet are "
+columns+" #");

// create a loop from 1 to number of columns inside resultset
System.out.println("# Structure of data inside "
+ "resultset is given below #");

for(int i = 1; i <= columns; i++)
{
// lets get the name of column of resultset which is available
// at given index
String columnName = rsmd.getColumnName(i);

// lets get the type of column of resultset which is available
// at given index
String columnType = rsmd.getColumnTypeName(i);

// show the index of column, its name, and its type
System.out.println("Index: "+i+", Name: "+columnName
+", Type: "+columnType);
}

// lets close the connection
co.close();

}
// any runtime error (bole toh exception) will be handled by the catch block
// e is the object of exception class
catch (Exception e)
{
System.out.println("Runtime error is "+e);
}

}
}

# First program to ends here #

# # # # # # # # # # # # # # # # # # 

# Second program to show the application of ResultSetMetaData #

note: save this code inside SecondApplicationOfResultSetMetaData.java file

import java.io.FileOutputStream;
import java.sql.*;
import java.util.Scanner;
public class SecondApplicationOfResultSetMetaData
{
public static void main(String[] args)
{
try
{
//  create object of scanner class to get input from keyboard
Scanner sc = new Scanner(System.in);

System.out.print("Enter the name of database: ");
String dbName = sc.nextLine();

System.out.print("Enter the name of the table: ");
String tableName = sc.nextLine();

//  load the driver class for MySQL server database
Class.forName("com.mysql.jdbc.Driver");

//  get object of connection to communicate with database
// note: co is the object name of connection
Connection co = DriverManager.getConnection
("jdbc:mysql://localhost:3306/"+dbName, "root","root");

//  get object of statement to make a dialog with database
// note: st is the object name of statement
Statement st = co.createStatement();

//  execute the select query
// note: rs is the object of resultset, which will keep the data of table
// note: here i have prefixed the name of database than dot (bole toh .)
// than the name of table
ResultSet rs = st.executeQuery("select * from "+dbName+"."+tableName);

//  get object of resultsetmetadata to know about resultset
// note: rsmd is the object of resultsetmetadata
ResultSetMetaData rsmd = rs.getMetaData();

//  get number of columns inside the resultset
int columns = rsmd.getColumnCount();

// in this string we will create html code
String result = "";

result = "<html>"
+ "<head>"
+ "<title>"
+ dbName+"_"+tableName
+ "</title>"
+ "</head>"
+ "<body>"
+ "<center>"
+ "<h3 style='color : red'>[dbname: "+dbName+"]</h3>"
+ "<h3 style='color : blue'>[tablename: "+tableName+"]</h3>"
// create html table
+ "<table border=1>";

for(int i = 1; i <= columns; i++)
{
String columnName = rsmd.getColumnName(i);

// concatenate the column-name in result along with some html
// th means table heading
result = result + "<th>" + columnName + "</th>";
}

// fetch a record from the result-set
while(rs.next())
{
// create a row in html table
// tr means table row
result = result + "<tr>";

// using this loop we will fetch all the columns of the record
// which was fetched by the rs.next() method
for(int i = 1; i <= columns; i++)
{
// get column name in result-set
String columnName = rsmd.getColumnName(i);

// fetch data of column from the result-set using column-name
String columnData = rs.getString(columnName);

// store the data of column inside the column in html table
// td means table-data
result = result +"<td>" +  columnData + "</td>";
}

// combine a row after each record
result = result + "<tr>";
}

// complete the table
result = result + "</table>"
+ "</body>"
// complte the html code
+ "</html>";

// directory to store a file
String directory = "C:\\Users\\admin\\Desktop\\";

// to store filename
String filename = dbName+"_"+tableName+".html";

// to store complete filepath
String filepath = directory + filename;

//  open a file in write mode
// this file will be created inside "C:\Users\admin\Desktop" location
// of our computer
FileOutputStream fo = new FileOutputStream
(filepath,false);

//  convert the string into array of byte
byte[] array = result.getBytes();

//  store the data of array inside the file in one go
fo.write(array);

//  show the message on console (bole toh eclipse console)
System.out.println("Please check "+dbName+"_"
+tableName+".html file"+ " in "
+directory+" location");

//  close the file
fo.close();

//  close the connection
co.close();

}
// runtime error (bole toh exception) will be handled by catch block
// here e is the object of exception class
catch (Exception e)
{
System.out.println("Runtime error is "+e);
}

}
}

# Second program ends here #

9 comments: