Unit 4 - DBMS
Unit 4 - DBMS
Java Application
Java DB API
1. Open a Connection
2. Send a statement
DBMS Engine
3. Retrieve results
4. Close a connection 1. Create a connection
Session
2. Execute statement
3. Send results
4. Close the session
JDBC driver type-1
• Uses the existing API
• Not the fastest
JDBC-ODBC Bridge Java
ODBC Driver
Native Driver
Non Java
Net Driver
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.
Native-API driver
JDBC driver type-3 & 4
• 100% java.
JDBC Driver
Implements a proprietary Java
Protocol in java
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.
Network Protocol driver
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.
Thin driver
Complete JDBC Architecture
Java Application
JDBC Interface
JDBC Driver Manager
JDBC Driver
JDBC Net JDBC–ODBC JDBC Driver C JDBC Driver D Interface
Driver A Bridge B
Native Driver B
A B C D
On Different Platforms
PC
MAC
DBMS
Unix
The java.sql package
• interfaces • Classes
– Driver interface – DriverManager
– Connection interface class
– Statement interface – Blob class
– PreparedStatement interface – Clob class
– CallableStatement interface – Types class
– ResultSet interface
– ResultSetMetaData interface
– DatabaseMetaData interface
– RowSet interface
Database Connectivity Steps
• There are 5 steps to connect any java
application with the database using JDBC.
These steps are as follows:
1. Register the Driver class
2. Create connection
3. Create statement
4. Execute queries
5. Close connection
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 Class
NotFoundException
• OracleDriver
– Class.forName("oracle.jdbc.driver.OracleDriver");
• MySql
– Class.forName("com.mysql.jdbc.Driver")
• PostgreSQL
– Class.forName("org.postgresql.Driver")
2. Create connection
• The getConnection() method of DriverManager class is
used to establish connection with the database
• Syntax of getConnection() method
– public static Connection getConnection(String url)throws S
QLException
– public static Connection getConnection(String url,String na
me,String password) throws SQLException
• To Establish connection with the Oracle database
– Connection con=DriverManager.getConnection( "jdbc:oracl
e:thin:@localhost:1521:xe","system","password");
29
4.Execute the query: ResultSet
String queryLehigh = "select * from Lehigh";
ResultSet rs = Stmt.executeQuery(queryLehigh);
//What does this statement do?
while (rs.next()) {
int ssn = rs.getInt("SSN");
String name = rs.getString("NAME");
int marks = rs.getInt("MARKS");
}
30
5.Close connection
• By closing connection object statement and
ResultSet will be closed automatically.
• The close() method of Connection interface is
used to close the connection
• Syntax
– public void close()throws SQLException
– con.close();
31
Merging Data from Multiple Tables
import java.sql.*;
public class join
{ public static void main (String arg [])
{ try
{
Class.forName ("oracle.jdbc.driver.oracleDriver");
Connection con = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:orcl",
"scott", "tiger");
Statement st = con.createStatement ();
String query = "select empno, ename, job, dname, loc from emp1, dept1 where
emp1.deptno=dept1.deptno";
ResultSet rs = st.executeQuery (query);
System.out.println ("empno\t ename \t job dname \t \t loc");
while (rs.next ()) {
int empno = rs.getInt (1);
String ename = rs.getString (2);
String job = rs.getString (3);
String dname = rs.getString (4);
String loc = rs.getString (5);
System.out.println (empno+ " "+ename+ " "+job+ " "+dname+ " "+ loc); }
st.close ();
con.close (); }
catch (Exception ee)
{ System.out.println(ee); } } }
OUTPUT
ResultSet Interface
1) public boolean next(): is used to move the cursor to the one row next
from the current position.
2) public boolean previous(): is used to move the cursor to the one row previous
from the current position.
3) public boolean first(): is used to move the cursor to the first row in result
set object.
4) public boolean last(): is used to move the cursor to the last row in result
set object.
5) public boolean absolute(int is used to move the cursor to the specified row
row): number in the ResultSet object.
6) public boolean relative(int is used to move the cursor to the relative row
row): number in the ResultSet object, it may be positive
or negative.
7) public int getInt(int is used to return the data of specified column index
columnIndex): of the current row as int.
8) public int getInt(String is used to return the data of specified column name
columnName): of the current row as int.
9) public String getString(int is used to return the data of specified column index
columnIndex): of the current row as String.
10) public String getString(String is used to return the data of specified column name
columnName): of the current row as String.
Prepared Statement
A Java JDBC PreparedStatement is a special kind of Java JDBC
Statement object with some useful additional features. Remember,
you need a Statement in order to execute either a query or
an update. You can use a Java JDBC PreparedStatement instead of
a Statement and benefit from the features of the PreparedStatement.
Example
String sql = "update people set firstname=?,lastname=? where
id=?";
PreparedStatement
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setString(1, "Gary");
preparedStatement.setString(2, "Larson");
preparedStatement.setLong (3, 123);
int rowsAffected = preparedStatement.executeUpdate();
Creating a PreparedStatement
Before you can use a PreparedStatement you must first create it.
You do so using the Connection.prepareStatement(), like this:.
Example:
preparedStatement.setLong(1, 123);
The first number (1) is the index of the parameter to insert the value for.
The second number (123) is the value to insert into the SQL statement.
Here is the same example with a bit more details:
Method Description
void It is true bydefault means
setAutoCommit(bool each transaction is
ean status) committed bydefault.
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
con.commit();
con.close();
}}
CallableStatement
CallableStatement interface is used to call the stored procedures
and functions.
must not have the return type. must have the return type.
CallableStatement.executeUpdate
Invoke this method if the stored procedure does not return result sets.
CallableStatement.executeQuery
Invoke this method if the stored procedure returns one result set.
You can invoke CallableStatement.executeQuery for a stored
procedure that returns no result sets if you set property
allowNullResultSetForExecuteQuery
to DB2BaseDataSource.YES (1). In that
case, CallableStatement.executeQuery returns null. This behavior
does not conform to the JDBC standard.
CallableStatement.execute
Invoke this method if the stored procedure returns multiple result
sets, or an unknown number of result sets.
5. If the stored procedure returns multiple result
sets, retrieve the result sets.
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
System.out.println("success");
} }
int ifcaret;
int ifcareas;
int xsbytes;
String errbuff;
Connection con;
CallableStatement cstmt;
ResultSet rs;
…
cstmt = con.prepareCall("CALL DSN8.DSN8ED2(?,?,?,?,?)");
// Create a CallableStatement object
cstmt.setString (1, "DISPLAY THREAD(*)"); // Set input parameter (Db2 command)
cstmt.registerOutParameter (2, Types.INTEGER); // Register output parameters
cstmt.registerOutParameter (3, Types.INTEGER);
cstmt.registerOutParameter (4, Types.INTEGER);
cstmt.registerOutParameter (5, Types.VARCHAR);
cstmt.executeUpdate(); // Call the stored procedure
ifcaret = cstmt.getInt(2); // Get the output parameter values
ifcareas = cstmt.getInt(3);
xsbytes = cstmt.getInt(4);
errbuff = cstmt.getString(5);
cstmt.close();