You are on page 1of 76

UCS18501- ADVANCED JAVA UCS

UCS18501-ADVANCED JAVA
PROGRAMMING - UNIT – I
1
2
CONTENTS
 RMI and DATABASE ACCESS
 Remote method invocation
 Overview of RMI
 Developing an RMI Application
 RMI over IIOP
 Overview of JDBC
 JDBC Drivers
 Connecting to a Database
 Statement Interfaces
 ResultSets, Using MetaData.

3
Remote Method Invocation – (RMI)

 The RMI (Remote Method Invocation) is an API that


provides a mechanism to create distributed application in
java.
 The RMI allows an object to invoke methods on an object
running in another JVM.
 The RMI provides remote communication between the
applications using two objects such as stub and skeleton.

4
Overview of RMI
 RMI uses stub and skeleton object for communication with the
remote object.
 A remote object is an object whose method can be invoked
from another JVM.
stub and skeleton:
 The stub is an object, acts as a gateway for the client side. All
the outgoing requests are routed through it.
 The skeleton is an object, acts as a gateway for the server side
object. All the incoming requests are routed through it.

5
Stub
 When the caller invokes method on the stub object, it does the
following tasks:
 It initiates a connection with remote Virtual Machine (JVM),
 It writes and transmits the parameters to the remote Virtual
Machine (JVM),
 It waits for the result
 It reads the return value or exception, and
 It finally, returns the value to the caller.

6
Skeleton
 It reads the parameter for the
remote method
 It invokes the method on the
actual remote object, and
 It writes and transmits the
result to the caller.

COMMUNICATION B/W MACHINE A AND MACHINE B

7
RMI Communication

8
RMI Layers and Components

9
RMI ARCHITECTURE

10
11
RMI LAYERS
 Application Layer
 This layer is nothing but the actual systems (client and server)
involved in communication. A client Java program communicates
with the other Java program on the server side. RMI is nothing but
a communication between two JVMs placed on different systems.
 Proxy Layer
 The client server communication goes through these proxies. Client
sends its request of method invocation (to be executed on remote
server) to stub. Stub in turn sends the request to skeleton.
 Skeleton passes the request to the server program. Server executes
the method and sends the return value to the skeleton (to route to
client). Skeleton sends to stub and stub to client program.
12
RMI LAYERS
 Remote Reference Layer
 Proxies are implicitly connected to RMI mechanism through
Remote reference layer, the layer responsible for object
communication and transfer of objects between client and server.
 Transport layer does not exist separately but is a part of
Remote reference layer. Transport layer is responsible for actually
setting up connections and handling the transport of data from
one machine to another. It can be modified to handle encrypted
streams, compression algorithms and a number of other
security/performance related enhancements.

13
Architecture of an RMI Application
 RMI is used to build distributed applications; it provides
remote communication between Java programs. It is provided
in the package java.rmi.
 Architecture of an RMI Application
 In an RMI application, we write two programs, a server
program (resides on the server) and a client
program (resides on the client).
 Inside the server program, a remote object is created and
reference of that object is made available for the client (using
the registry).
 The client program requests the remote objects on the server
and tries to invoke its methods.

14
Working of an RMI Application
 When the client makes a call to the remote object, it is received
by the stub which eventually passes this request to the RRL.
 When the client-side RRL receives the request, it invokes a
method called invoke() of the object remoteRef. It passes the
request to the RRL on the server side.
 The RRL on the server side passes the request to the Skeleton
(proxy on the server) which finally invokes the required object
on the server.
 The result is passed all the way back to the client.

15
Marshaling and Unmarshaling
 Marshaling is nothing but converting data into a special
format suitable to pass through the distributed environment
without loosing object persistence. For this reason, the
 RMI mechanism implicitly serialize the objects involved in
communication.
 The stub marshals the data of client and then sends to the
skeleton.
 As the format is not understood by the server program, it is
unmarshaled by the skeleton into the original format and
passed to server. Similarly from server to client also.
 Marshaling and unmarshaling are done by the RMI
runtime mechanism implicitly without any programmers
extra coding.
16
RMI Registry

 RMI registry is a namespace on which all server objects are


placed.
 Each time the server creates an object, it registers this object
with the RMI registry (using bind() or reBind() methods).
 These are registered using a unique name known as bind
name.
 To invoke a remote object, the client needs a reference of that
object.
 At that time, the client fetches the object from the registry
using its bind name (using lookup() method).

17
18
19
Goals of RMI

 To minimize the complexity of the application.


 To preserve type safety.
 Distributed garbage collection.
 Minimize the difference between working with local and
remote objects
 Invocation of object methods in another Java virtual machine
 Ability to pass/return Java primitives and objects
 Distribution transparency (Java semantics)
 Easy to use

20
 Understanding requirements for the distributed
applications

 The application need to locate the remote method


 It need to provide the communication with the remote objects,
and
 The application need to load the class definitions for the objects.
 The RMI application have all these features, so it is called the
distributed application.

21
Developing an RMI Application

 Create the remote interface


 Provide the implementation of the remote interface
 Compile the implementation class and create the stub and
skeleton objects using the rmic tool
 Start the registry service by rmiregistry tool
 Create and start the remote application
 Create and start the client application

22
Working of RMI Application
 The client application need only two files, remote interface
and client application.
 In the rmi application, both client and server interacts with
the remote interface.
 The client application invokes methods on the proxy object,
RMI sends the request to the remote JVM.
 The return value is sent back to the proxy object and then to
the client application.

23
RMI PROGRAM ARCHITECTURE

24
1.Create The Remote Interface
 For creating the remote interface, extend the Remote
interface and declare the RemoteException with all the
methods of the remote interface.
 Here, we are creating a remote interface that extends the
Remote interface. There is only one method named add() and
it declares RemoteException.
 import java.rmi.*;
 public interface Adder extends Remote{
 public int add(int x,int y)throws RemoteException;
 }

25
2.Provide the implementation of the remote interface

 For providing the implementation of the Remote interface, we


need to Either extend the UnicastRemoteObject class,
 or use the exportObject() method of the UnicastRemoteObject
class
 import java.rmi.*;
 import java.rmi.server.*;
 public class AdderRemote extends UnicastRemoteObject implements Ad
der{
 AdderRemote()throws RemoteException{
 super();
 }
 public int add(int x,int y){return x+y;}
 }

26
 3.Create the stub and skeleton objects using the rmic
tool.
 Next step is to create stub and skeleton objects using the rmi
compiler. The rmic tool invokes the RMI compiler and creates stub
and skeleton objects.
 rmic AdderRemote
 4. Start the registry service by the rmiregistry tool
 Now start the registry service by using the rmiregistry tool. If you
don't specify the port number, it uses a default port number.
 In this example, we are using the port number 5000.
 rmiregistry 5000

27
5) Create and run the server
application
 Now rmi services need to be hosted in a server process. The
Naming class provides methods to get and store the remote
object.
 import java.rmi.*;
 import java.rmi.registry.*;
 public class MyServer{
 public static void main(String args[]){
 try{
 Adder stub=new AdderRemote();
 Naming.rebind("rmi://localhost:5000/sonoo",stub);
 }catch(Exception e){System.out.println(e);} } }
28
6) Create and run the client application

 At the client we are getting the stub object by the lookup()


method of the Naming class and invoking the method on this
object.
 In this example, we are running the server and client
applications, in the same machine so we are using localhost.
 If you want to access the remote object from another
machine, change the localhost to the host name (or IP
address) where the remote object is located.

29
The Client Application
 import java.rmi.*;
 public class MyClient{
 public static void main(String args[]){
 try{
 Adder stub=(Adder)Naming.lookup("rmi://localhost:5000
/sonoo");
 System.out.println(stub.add(34,4));
 }catch(Exception e){}
 }
 }

30
STEPS TO EXECUTE THE PROGRAM
 For running this rmi example,
 1) compile all the java files javac *.java
2)create stub and skeleton object by rmic tool
 rmic AdderRemote
 3)start rmi registry in one command prompt
 rmiregistry 5000
 4)start the server in another command prompt
 java MyServer
 5)start the client application in another command prompt
 java MyClient

31
Overview of RMIOverIIOP
 RMI-IIOP denotes the Java Remote Method Invocation
(RMI) interface over the Internet Inter-Orb Protocol
(IIOP), which delivers Common Object Request Broker
Architecture (CORBA) distributed computing capabilities to
the Java platform.
 RMI-IIOP provides interoperability with other CORBA
objects implemented in various languages - but only if all the
remote interfaces are originally defined as Java RMI
interfaces
 RMI-IIOP combines the best features of Java Remote Method
Invocation (RMI) with the best features of CORBA.
32
Overview of RMIOverIIOP
 RMI-IIOP is based on open standards defined with the
participation of hundreds of vendors and users in the Object
Management Group.
 Like CORBA, RMI-IIOP uses Internet Inter-ORB Protocol
(IIOP) as its communication protocol.
 IIOP eases legacy application and platform integration by
allowing application components written in C++, Smalltalk,
and other CORBA supported languages to communicate
with components running on the Java platform.

33
Java JDBC Drivers
 DBC stands for Java Database Connectivity. JDBC is a
Java API to connect and execute the query with the
database. It is a part of JavaSE (Java Standard Edition).
JDBC API uses JDBC drivers to connect with the
database.
 There are four types of JDBC drivers:
 JDBC-ODBC bridge driver
 Native-API driver (partially java driver)
 Network Protocol driver (fully java driver)
 Thin driver (fully java driver)

34
JDBC-ODBC bridge driver
 The JDBC-ODBC bridge driver uses ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method calls
into the ODBC function calls. This is now discouraged because of thin
driver.
 Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle
recommends that you use JDBC drivers provided by the vendor of your
database instead of the JDBC-ODBC Bridge.
 Advantages:
 easy to use.
 can be easily connected to any database.
 Disadvantages:
 Performance degraded because JDBC method call is converted into the
ODBC function calls.
 The ODBC driver needs to be installed on the client machine.
35
JDBC-ODBC bridge driver

36
Native-API driver

 The Native API driver uses the client-side libraries of the


database. The driver converts JDBC method calls into native
calls of the database API. It is not written entirely in java.
 Advantage:
 performance upgraded than JDBC-ODBC bridge driver.
 Disadvantage:
 The Native driver needs to be installed on the each client
machine.
 The Vendor client library needs to be installed on client
machine.

37
Native-API driver

38
Network Protocol driver
 The Network Protocol driver uses middleware (application server)
that converts JDBC calls directly or indirectly into the vendor-
specific database protocol. It is fully written in java.
 Advantage:
 No client side library is required because of application server that
can perform many tasks like auditing, load balancing, logging etc.
 Disadvantages:
 Network support is required on client machine.
 Requires database-specific coding to be done in the middle tier.
 Maintenance of Network Protocol driver becomes costly because it
requires database-specific coding to be done in the middle tier.

39
Network Protocol driver

40
Thin driver

 The thin driver converts JDBC calls directly into the vendor-
specific database protocol. That is why it is known as thin
driver. It is fully written in Java language.
 Advantage:
 Better performance than all other drivers.
 No software is required at client side or server side.
 Disadvantage:
 Drivers depend on the Database.

41
Thin driver

42
JDBC API
 We can use JDBC API to access
tabular data stored in any
relational database.
 By the help of JDBC API, we
can save, update, delete and
fetch data from the database.
 It is like Open Database
Connectivity (ODBC) provided
by Microsoft.

43
Why Should We Use JDBC?
 Before JDBC, ODBC API was the database API to connect and
execute the query with the database.
 But, ODBC API uses ODBC driver which is written in C
language (i.e. platform dependent and unsecured). That is why
Java has defined its own API (JDBC API) that uses JDBC drivers
(written in Java language).
 We can use JDBC API to handle database using Java
program and can perform the following activities:
 Connect to the database
 Execute queries and update statements to the database
 Retrieve the result received from the database.

44
Connecting to a Database using JDBC
 There are 5 steps to connect any java application with the
database using JDBC. These steps are as follows:
 Register the Driver class
 Create connection
 Create statement
 Execute queries
 Close connection

45
1) Register the driver class
 The forName() method of Class class is used to register the
driver class. This method is used to dynamically load the
driver class.
 Syntax of forName() method
 public static void forName(String className)throws
ClassNotFoundException
 Example to register the OracleDriver class
 Class.forName("oracle.jdbc.driver.OracleDriver");

46
2) Create the connection object
 The getConnection() method of DriverManager class is used to
establish connection with the database.
 Syntax of getConnection() method
 1) public static Connection getConnection(String url)throws SQ
LException
 2) public static Connection getConnection(String url,String name,
String password)
 throws SQLException
 Example to establish connection with the Oracle database
 Connection con=DriverManager.getConnection(
 "jdbc:oracle:thin:@localhost:1521:xe","system","password");

47
3) Create the Statement object

 The createStatement() method of Connection interface is


used to create statement. The object of statement is
responsible to execute queries with the database.
 Syntax of createStatement() method
 public Statement createStatement()throws SQLException
Example to create the statement object
 Statement stmt=con.createStatement();

48
4) Execute the query
 The executeQuery() method of Statement interface is used to execute
queries to the database. This method returns the object of ResultSet
that can be used to get all the records of a table.Syntax of
executeQuery() method
 public ResultSet executeQuery(String sql)throws SQLException
 Example to execute query
 ResultSet rs=stmt.executeQuery("select * from emp");

 while(rs.next()){
 System.out.println(rs.getInt(1)+" "+rs.getString(2));
 }

49
5) Close the connection object

 By closing connection object statement and ResultSet will be


closed automatically. The close() method of Connection
interface is used to close the connection.Syntax of close()
method
 public void close()throws SQLException
 Example to close connection
 con.close();

50
Java Database Connectivity with Oracle
 Driver class: The driver class for the oracle database
is oracle.jdbc.driver.OracleDriver.
 Connection URL: The connection URL for the oracle10G
database is jdbc:oracle:thin:@localhost:1521:xe where
jdbc is the API, oracle is the database, thin is the driver, localhost
is the server name on which oracle is running, we may also use
IP address, 1521 is the port number and XE is the Oracle service
name.You may get all these information from the tnsnames.ora
file.
 Username: The default username for the oracle database
is system.
 Password: It is the password given by the user at the time of
installing the oracle database.

51
Create a Table in oracle

 Before establishing connection, let's first create a table in


oracle database.
 Following is the SQL query to create a table.
 create table emp(id number(10),name varchar2(40),age numb
er(3));

52
Example to Connect Java Application with
Oracle database
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

//step5 close the connection object


con.close(); }catch(Exception e){ System.out.println(e);} } }
53
d
Two ways to load the jar file:
 paste the ojdbc14.jar file in jre/lib/ext folder
 set classpath
 2) set classpath:
 How to set the temporary classpath:
 Firstly, search the ojdbc14.jar file then open command prompt and
write:
 C:>set classpath=c:\folder\ojdbc14.jar;.;
 How to set the permanent classpath:
 Go to environment variable then click on new tab. In variable name
write classpath and in variable value paste the path to ojdbc14.jar
by appending ojdbc14.jar;.; as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14
.jar;.;

54
A list of popular interfaces of JDBC API
are given below:
 Driver interface
 Connection interface
 Statement interface
 PreparedStatement interface
 CallableStatement interface
 ResultSet interface
 ResultSetMetaData interface
 DatabaseMetaData interface
 RowSet interface
 A list of popular classes of JDBC API are given below:
 DriverManager class
 Blob class
 Clob class
 Types class
55
Statement Interfaces
 Once a connection is obtained we can interact with the database.
 The JDBC Statement, CallableStatement, and
 PreparedStatement interfaces define the methods and properties that
enable you to send SQL or PL/SQL commands and receive data from
your database.
 The Statement Objects
 Creating Statement Object
 Before you can use a Statement object to execute a SQL statement,
you need to create one using the Connection object's
createStatement( ) method, as in the following example −
 Statement stmt = null; try { stmt = conn.createStatement( ); . . . }
catch (SQLException e) { . . . } finally { . . . }

56
The Statement Objects
Object
 Closing Statement Object
 Statement stmt = null; try { stmt = conn.createStatement( ); . . . }
catch (SQLException e) { . . . } finally { stmt.close(); }
 boolean execute (String SQL): Returns a boolean value of true if a
ResultSet object can be retrieved; otherwise, it returns false. Use this
method to execute SQL DDL statements or when you need to use truly
dynamic SQL.
 int executeUpdate (String SQL) − Returns the number of rows
affected by the execution of the SQL statement. Use this method to
execute SQL statements for which you expect to get a number of rows
affected - for example, an INSERT, UPDATE, or DELETE statement.
 ResultSet executeQuery (String SQL) − Returns a ResultSet
object. Use this method when you expect to get a result set, as you
would with a SELECT statement.

57
The Statement Objects
Object

58
The PreparedStatement Objects
 The PreparedStatement interface extends the Statement
interface, which gives you added functionality with a couple
of advantages over a generic Statement object.
 This statement gives you the flexibility of supplying
arguments dynamically.
 Creating PreparedStatement Object
 PreparedStatement pstmt = null;
 try { String SQL = "Update Employees SET age = ?
WHERE id = ?"; pstmt = conn.prepareStatement(SQL); . . .
} catch (SQLException e) { . . . } finally { . . . }

59
The PreparedStatement Objects
 All parameters in JDBC are represented by the ? symbol, which is
known as the parameter marker.
 If you forget to supply the values, you will receive an
SQLException.
 All of the Statement object's methods for interacting with the
database (a) execute(), (b) executeQuery(), and (c) executeUpdate()
also work with the PreparedStatement object.
 Closing PreparedStatement Object
 PreparedStatement pstmt = null;
 try { String SQL = "Update Employees SET age = ? WHERE id =
?"; pstmt = conn.prepareStatement(SQL); . . . }
 catch (SQLException e) { . . . } finally { pstmt.close(); }
60
The CallableStatement Objects
 Just as a Connection object creates the Statement and
PreparedStatement objects, it also creates the CallableStatement
object, which would be used to execute a call to a database stored
procedure.
 Creating CallableStatement Object
 Suppose, you need to execute the following Oracle stored
procedure −
 CREATE OR REPLACE PROCEDURE getEmpName (EMP_ID
IN NUMBER, EMP_FIRST OUT VARCHAR) AS
 BEGIN
 SELECT first INTO EMP_FIRST FROM Employees WHERE ID
= EMP_ID;
 END;

61
The CallableStatement Objects

 DELIMITER $$
 DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$
 CREATE PROCEDURE `EMP`.`getEmpName` (IN
EMP_ID INT, OUT EMP_FIRST VARCHAR(255)) BEGIN
SELECT first INTO EMP_FIRST FROM Employees
WHERE ID = EMP_ID;
 END $$
 DELIMITER ;

62
The CallableStatement Objects

63
The CallableStatement Objects

 Connection.prepareCall() method to instantiate


a CallableStatement object based on the preceding stored
procedure.
 CallableStatement cstmt = null; try { String SQL = "{call
getEmpName (?, ?)}"; cstmt = conn.prepareCall (SQL); . . .
} catch (SQLException e) { . . . } finally { . . . }
 Closing CallableStatement Object
 CallableStatement cstmt = null; try { String SQL = "{call
getEmpName (?, ?)}"; cstmt = conn.prepareCall (SQL); . . .
} catch (SQLException e) { . . . } finally { cstmt.close(); }

64
JDBC ResultSet Interface
 There are 3 types in ResultSet.
 They are:
 TYPE_FORWARD_ONLY: It is the default option, where
the cursor moves from start to end i.e. in the forward
direction.
 TYPE_SCROLL_INSENSITIVE: In this type, it will make
the cursor to move in both forward and backward.
 TYPE_SCROLL_SENSITIVE: It is similar to
TYPE_SCROLL_INSENSITIVE, the difference is if anyone
updates the data after the SQL Query has returned the data,
while iterating it will reflect the changes to the dataset.

65
JDBC ResultSet Interface
 ResultSet Concurrency
 There are 2 modes of Concurrency in ResultSet.
They are:
 ResultSet.CONCUR_READ_ONLY: It is the default
concurrency mode. We can only read the data in the
ResultSet. Updation is not applicable.
 ResultSet.CONCUR_UPDATABLE:We can update the
data in the ResultSet object.

66
Methods In ResultSet Interface
 There are 4 categories of ResultSet methods.
 They are:
 Navigational Methods
 Getter Methods
 Setter Methods
 Miscellaneous Methods

Navigational Methods

 This method is used to move the cursor around the dataset.


 Boolean absolute(int row): It is used to move the cursor to the specified
row which is mentioned in the parameter and return true if the operation is
successful else return false.
 Void afterLast(): It makes the ResultSet cursor to move after the last row.
 Void beforeFirst(): It makes the ResultSet cursor to move before the first
row.

67
Navigational Methods
 Boolean first(): It makes the ResultSet cursor to move to the first row. It returns
True if the operation is successful else False.
 Boolean last(): It makes the ResultSet cursor to move to the last row. It returns
True if the operation is successful else False.
 Boolean next(): It makes the ResultSet cursor to move to the next row. It returns
True if there are more records and False if there are no more records.
 Boolean previous(): It makes the ResultSet cursor to move to the previous row. It
returnsTrue if the operation is successful else False.
 Boolean relative(): It moves the cursor to the given number of rows either in the
forward or backward direction.
 Int getRow(): It returns the current row number the ResultSet object is pointing
now.
 Void moveToCurrentRow(): It moves the cursor back to the current row if it is
currently in insert row.
 Void moveToInsertRow(): It moves the cursor to the specific row to insert the
row into the Database. It remembers the current cursor location.
68
2) Getter Methods
 ResultSet has stored the data of the table from the Database. Getter
methods are used to get the values of the table in ResultSet. For that, we
need to pass either column Index value or Column Name.
 The following are the getter methods in ResultSet:
 int getInt(int ColumnIndex): It is used to get the value of the
specified column Index as an int data type.
 float getFloat(int ColumnIndex): It is used to get the value of the
specified column Index as a float data type.
 java.sql.date getDate(int ColumnIndex): It is used to get the
value of the specified column Index as a date value.
 int getInt(String ColumnName): It is used to get the value of the
specified column as an int data type.
 float getFloat(String ColumnName): It is used to get the value of
the specified column as a float data type.
 Java.sql.date getDate(String ColumnName): It is used to get the
value of the specified column as a date value.

69
Setter/Updater Methods
 We can update the value in the Database using ResultSet Updater
methods. It is similar to Getter methods, but here we need to pass the
values/ data for the particular column to update in the Database.
 The following are the updater methods in ResultSet:
 void updateInt(int ColumnIndex, int Value): It is used to update
the value of the specified column Index with an int value.
 void updateFloat(int ColumnIndex, float f): It is used to update
the value of the specified column Index with the float value.
 void updateDate(int ColumnIndex, Date d): It is used to update
the value of the specified column Index with the date value.
 void updateInt(String ColumnName, int Value): It is used to
update the value of the specified column with the given int value.
 void updateFloat(String ColumnName, float f): It is used to
update the value of the specified column with the given float value.
 Java.sql.date getDate(String ColumnName): It is used to update
the value of the specified column with the given date value.

70
ResultSet Miscellaneous Methods

 void close() throws SQLException: This method frees up


resources associated with ResultSet Instance. It must be
called otherwise it will result in resource leakage.
 ResultSetMetaData getMetaData() throws SQLExceptio
n: This method returns ResultSetMetaData instance. It gives
information about the type and property of columns of the
query output.

71
UsingMetaDatainterface in Java
Java ResultSetMetaData Interface
Java DatabaseMetaData interface
Java ResultSetMetaData Interface
The metadata means data about data i.e. we can get
further information from the data.
If you have to get metadata of a table like total number of
column, column name, column type etc.
ResultSetMetaData interface is useful because it provides
methods to get metadata from the ResultSet object.

72
Description
Method

public int getColumnCount()throws SQLException it returns the total number of columns in the
ResultSet object.

public String getColumnName(int index)throws it returns the column name of the specified
SQLException column index.
public String getColumnTypeName(int index)throws it returns the column type name for the specified
SQLException index.

public String getTableName(int index)throws it returns the table name for the specified column
SQLException index.
Exampleof ResultSetMetaDatainterface:
import java.sql.*;

class Rsmd{
public static void main(String args[]){
try{ Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("select * from emp");

ResultSet rs=ps.executeQuery();

ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("Total columns: "+rsmd.getColumnCount());


System.out.println("Column Name of 1st column:"+rsmd.getColumnName(1));

System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));


con.close();

}catch(Exception e){ System.out.println(e);}


}

74
Java DatabaseMetaData interface
DatabaseMetaData interface provides methods to get meta data of a database such as database
product name, database product version, driver name, name of total number of tables, name
of total number of views etc.
Commonly used methods of DatabaseMetaData interface
public String getDriverName()throws SQLException: it returns the name of the
JDBC driver.
public String getDriverVersion()throws SQLException: it returns the version number
of the JDBC driver.
public String getUserName()throws SQLException: it returns the username of the
database.
public String getDatabaseProductName()throws SQLException: it returns the
product name of the database.
public String getDatabaseProductVersion()throws SQLException: it returns the
product version of the
database.
public ResultSet getTables(String catalog, String schemaPattern, String
tableNamePattern, String[] types)throws SQLException: it returns the description of
the tables of the specified catalog. The table type can be TABLE, VIEW, ALIAS, SYSTEM
TABLE, SYNONYM etc.
Simple Example of DatabaseMetaData interface:
import java.sql.*;
class Dbmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
DatabaseMetaData dbmd=con.getMetaData(); System.out.println("Driver Name:
"+dbmd.getDriverName()); System.out.println("Driver Version:
"+dbmd.getDriverVersion());
System.out.println("UserName: "+dbmd.getUserName()); System.out.println("Database
Product Name: "+dbmd.getDatabaseProductName()); System.out.println("Database
Product Version: "+dbmd.getDatabaseProductVersion());
con.close();
}
catch(Exception e){ System.out.println(e);}} }

You might also like