Wednesday, 1 October 2014

Database Metadata

Metadata is the data that describes about data. Database metadata describes about specific characteristic of each data item in the database.

For example, Database metadata describes about tables, columns in each table, views in database, information about stored procedures.

JDBC provides below interfaces, to deal with database metadata.

DatabaseMetaData interface: provides information about the database

ResultSetMetaData interface: provides information about the columns of a ResultSet object

ParameterMetaData interface: provides information about the parameters to PreparedStatement commands

As you observe above image, the database 'world' has tables city, country, countrylanguage. Will retrieve the same information using jdbc.

/* Step 1: Import sql package */
import java.sql.*;

public class SampleApp {
    
    /* Update username, password and driver details here */
    static Connection getConnection() throws ClassNotFoundException, SQLException{
         /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");  
       
        Class.forName("com.mysql.jdbc.Driver");
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/world";
        String userName = "root";
        String pasword = "tiger";
        return DriverManager.getConnection(url, userName, pasword);
    }
    
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        Connection conn = getConnection();
        ResultSet rs = null;
        /* Create table employee */
        String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
        DatabaseMetaData meta = conn.getMetaData();
        
        if(meta == null){
            System.out.println("No Support");
        }
        else{
            rs = meta.getTables(null, null, "%", null);
            while(rs.next()){
                System.out.println(rs.getString(3));
            }
        }
    rs.close();
        conn.close();
    }
}

Output
Loading/Registering driver
Connecting to database
city
country
countrylanguage

String url = "jdbc:mysql://localhost/world";
Above url is used to connect to database 'world'.

DatabaseMetaData meta = conn.getMetaData();
Retrieves a DatabaseMetaData object that contains metadata about the database to which this Connection object represents a connection.







Prevoius                                                 Next                                                 Home

No comments:

Post a Comment