JDBC Meta Data Get tables

JDBC Meta Data is the collective information about the data structure and
property of a column available in table. The meta data of any table tells you
the name of the columns,datatype used in column and constraint used to enter the
value of data into column of the table.
Understand with Example The Tutorial helps you to know
understand an example from JDBC Metadata Get table. In this program, the
code describe you JDBC Meta Data Get tables that explain the column
property and structure of table. The class Jdbc MetaDataGettables include
the list of methods to get the meta data property of table as given follow
- Loading
a driver by calling a class.forname( ),this accept driver class as argument.
DriverManager.getConnection
( ) -This method return you a connection object and built a connection between url and
database. Once a connection is built, a
front end can access, insert ,update and retrieve the data in the backend
database. con.createStatement ( ) -This is used to create a sql object. An
object of connection class is used to send and create a sql query in the
database backend. executeQuery ( ) -The method retrieve a record set from a table in
database. The retrieve record set
is assigned to a result set. getMetaData ( ) - The
Result Set call get Metadata( ),which return you the
property of the retrieve record set (length,field,column).Meta Data account
for data element and its attribute. getcolumncount ( )
-The method return you a integer data type and provides you the number of column in the
Result set object. Finally the println print the table name, field, size
and data type. In case there is an exception in the try block The
subsequent catch block caught and handle the exception. JdbcMetaDataGettables.java
import java.sql.*;
public class JdbcMetaDataGettables {
static public final String driver = "com.mysql.jdbc.Driver";
static public final String connection =
"jdbc:mysql://localhost:3306/komal";
static public final String user = "root";
static public final String password = "root";
public static void main(String args[]) {
try {
Class.forName(driver);
Connection con =
DriverManager.getConnection(connection, user, password);
Statement st = con.createStatement();
String sql = "select * from person";
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int rowCount = metaData.getColumnCount();
System.out.println("Table Name : " + metaData.getTableName(2));
System.out.println("Field \tsize\tDataType");
for (int i = 0; i < rowCount; i++) {
System.out.print(metaData.getColumnName(i + 1) + " \t");
System.out.print(metaData.getColumnDisplaySize(i + 1) + "\t");
System.out.println(metaData.getColumnTypeName(i + 1));
}
} catch (Exception e) {
System.out.println(e);
}
}
}
|
Output
Table Name : person
Field size DataType
id 2 VARCHAR
cname 50 VARCHAR
dob 10 DATE
|
Download code

|