ResultSetMetaData Interface In Java
ResultSetMetaData Interface
In JDBC, metadata means data about the data, that is to say, we can get further information from the data and if we have to get metadata of a table like total number of columns, columns name, columns type etc. ResultSetMetaData interface is very useful because it provides methods to get metadata from the ResultSet object.
Methods of ResultSetMetaData interface
public int getColumnCount()throws SQLException
This method is used to return the total number of columns in the ResultSet object.
public String getColumnName(int index)throws SQLException
This method is used to return the column name of the specified column index.
public String getColumnTypeName(int index)throws SQLException
This method is used to return the column type name for the specified index.
public String getTableName(int index)throws SQLException
This method is used to return the table name for the specified column index.
Get the ResultSetMetaData object
The getMetaData() method of ResultSet interface is used to return the object of ResultSetMetaData.
Syntax
public ResultSetMetaData getMetaData()throws SQLException
Let’s see an example, given below.
Code
- import java.sql.*;
- public class StudentDatabase2 {
- public static void main(String args[]) throws Exception {
- Class.forName("org.apache.derby.jdbc.ClientDriver");
- String url = "jdbc:derby://localhost:1527/Student";
- String username = "Student";
- String password = "student";
- Connection conn = DriverManager.getConnection(url, username, password);
- PreparedStatement ps = conn.prepareStatement("select * from STUDENT.STUDENTDB");
- ResultSet rs = ps.executeQuery();
- ResultSetMetaData re = rs.getMetaData();
- System.out.println("Total Columns: " + re.getColumnCount());
- System.out.println("Column Name of 1st column: " + re.getColumnName(1));
- System.out.println("Column Type Name of 1st column: " + re.getColumnTypeName(1));
- conn.close();
- }
- }
Output
Summary
Thus, we learnt, JDBC Metadata means data about data, which states we can get the further information from the data and if we have to get the metadata of a table like total number of columns, columns name, columns type etc. and also learnt its important methods in Java.