0% found this document useful (0 votes)
22 views

Unit 4 - DBMS

uuuuu

Uploaded by

Saumya agarwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Unit 4 - DBMS

uuuuu

Uploaded by

Saumya agarwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

JDBC

Java Database Connectivity


• JDBC 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.
• The current version of JDBC is 4.3(September 2017)

There are four types of JDBC drivers:


1. JDBC-ODBC Bridge Driver,
2. Native Driver,
3. Network Protocol Driver, and
4. Thin Driver
Why to Learn JDBC?
JDBC stands for Java Database Connectivity, which is a
standard Java API for database-independent
connectivity between the Java programming language
and a wide range of databases.
The JDBC library includes APIs for each of the tasks
mentioned below that are commonly associated with
database usage.
• Making a connection to a database.
• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & Modifying the resulting records.
What you expect in DB API

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
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.
• 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.
JDBC-ODBC bridge driver
JDBC driver type-2
• Uses vendor-provided local libraries
• Most efficient

JDBC Driver Java

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 – Net Driver 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

ODBC Driver Native Driver C

Native Driver B

A B C D
On Different Platforms

JDBC API JDBC Driver


Classes

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");

URL UserID & password


2. Create connection: 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
• 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.
• Password: It is the password given by the user at the time of
installing the oracle database.
• ojdbc14.jar  Driver
2. Create connection: mysql
• Driver class: mysql database
– com.mysql.jdbc.Driver.
• Connection URL:
– jdbc:mysql://localhost:3306/sonoo
– jdbc is the API, mysql is the database
– localhost is the server name( may be IP address)
– 3306 is the port number and sonoo is the database name.
• Username: The default username for the mysql
database is root.
• Password: It is the password given by the user at the
time of installing the mysql database.
• mysql-connector.jar  Driver
2. Create connection: postgresql
• PostgreSQL™:
– jdbc:postgresql:database
– jdbc:postgresql://host/database
– jdbc:postgresql://host:port/database
• Host : The host name of the server.
– Defaults to localhost(IPv6 address), for example:
• jdbc:postgresql://[::1]:5740/accounting
• Port: The port number ( PostgreSQL™ standard port number (5432))
• Database: The database name.
• DriverManager.getConnection() method:
– Connection db = DriverManager.getConnection(url, username,
password);
• postgresql-8.0-310.jdbc3.jar  Driver
3. Create JDBC statement(s)
• The createStatement() method of Connection
interface is used to create statement.
• The object of statement is responsible to execute
queries with the database
• Creates a Statement object for sending SQL
statements to the database
• Syntax
– public Statement createStatement()throws SQLExcept
ion
– Statement stmt = con.createStatement() ;
25
Statement type
• 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.
Interfaces Recommended Use
Statement Use this for general-purpose access to your database. Useful
when you are using static SQL statements at runtime. The
Statement interface cannot accept parameters.
PreparedStatement Use this when you plan to use the SQL statements many times.
The PreparedStatement interface accepts input parameters at
runtime.
CallableStatement Use this when you want to access the database stored
procedures. The CallableStatement interface can also accept
runtime input parameters.
Statement
• After Creating Statement Object
• you can then use it to execute an SQL statement
– public 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.
– public 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.
– public 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.
– public int[] executeBatch(): is used to execute batch of commands.
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
– public ResultSet executeQuery(String sql)throws S
QLException
4.Execute the query: Create
• String createLehigh = "Create table Lehigh " +
"(SSN Integer not null, Name VARCHAR(32), " +
"Marks Integer)";
stmt.executeUpdate(createLehigh);
//What does this statement do?

• String insertLehigh = "Insert into Lehigh values“


+ "(123456789,abc,100)";
stmt.executeUpdate(insertLehigh);

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.

The Java JDBC PreparedStatement primary features are:

• Easy to insert parameters into the SQL statement.


• Easy to reuse the PreparedStatement with new parameter values.
• May increase performance of executed statements.
• Enables easier batch updates.

• public PreparedStatement prepareStatement(String query)throw


s SQLException{}
Below example shows, how to insert parameters into SQL
statements in this text, and also how to reuse
a PreparedStatement. The batch updates is explained in a
separate text.

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:.

String sql = "select * from people where id=?";


PreparedStatement preparedStatement = connection.prepareStatement(sql);

The PreparedStatement is now ready to have parameters inserted.

Inserting Parameters into a PreparedStatement


Everywhere you need to insert a parameter into your SQL, you write a question mark
(?).
For instance:

String sql = "select * from people where id=?";


Once a PreparedStatement is created (prepared) for the above SQL
statement, you can insert parameters at the location of the question mark.
This is done using the many setXXX() methods.

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:

String sql = "select * from people where id=?";


PreparedStatement
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setLong(123);
Executing the PreparedStatement

Executing the PreparedStatement looks like executing a regular Statement.


To execute a query, call the executeQuery() or executeUpdate method. Here
is an executeQuery() example:

String sql = "select * from people where firstname=? and lastname=?";


PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "John");
preparedStatement.setString(2, "Smith");
ResultSet result = preparedStatement.executeQuery();
Reusing a PreparedStatement
Once a PreparedStatement is prepared, it can be reused after execution.
You reuse a PreparedStatement by setting new values for the
parameters and then execute it again.
A simple 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();
preparedStatement.setString(1, "Stan");
preparedStatement.setString(2, "Lee");
preparedStatement.setLong (3, 456);
int rowsAffected = preparedStatement.executeUpdate();
PreparedStatement
Method Description
public void setInt(int paramIndex, int sets the integer value to the given
value) parameter index.
public void setString(int paramIndex, sets the String value to the given parameter
String value) index.
public void setFloat(int paramIndex, sets the float value to the given parameter
float value) index.
public void setDouble(int paramIndex, sets the double value to the given
double value) parameter index.
public int executeUpdate() executes the query. It is used for create,
drop, insert, update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an


instance of ResultSet.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Employees";
static final String UPDATE_QUERY = "UPDATE Employees set age=? WHERE id=?";

public static void main(String[] args) {


// Open a connection
try{ Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement stmt = conn.prepareStatement(UPDATE_QUERY);

// Bind values into the parameters.


stmt.setInt(1, 35); // This would set age
stmt.setInt(2, 102); // This would set ID
public static void main(String[] args) {
// Open a connection
try{
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement stmt = conn.prepareStatement(UPDATE_QUERY);

// Bind values into the parameters.


stmt.setInt(1, 35); // This would set age
stmt.setInt(2, 102); // This would set ID

// Let us update age of the record with ID = 102;


int rows = stmt.executeUpdate();
System.out.println("Rows impacted : " + rows );

// Let us select all the records and display them.


ResultSet rs = stmt.executeQuery(QUERY);

// Extract data from result set


while (rs.next()) {
// Retrieve by column name
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first")); Return value is : false
System.out.println(", Last: " + rs.getString("last")); Rows impacted : 1
}
rs.close(); ID: 100, Age: 18, First: ABC, Last: XYZ
} catch (SQLException e) { ID: 101, Age: 25, First: ACD, Last: YZ1
e.printStackTrace();
}
ID: 102, Age: 35, First: ZZZ, Last: KLM
} ID: 103, Age: 30, First: SSS, Last: MMM
}
ArrayList Example
public ArrayList<student> getResult(String qstr){
try{
if(!isInitialized) return null; // Create Connection ?
stmnt = con.createStatement();
rslt=stmnt.executeQuery(qstr); // Execute QUERY and get result
ArrayList<student> std=new ArrayList<student>(); // create ArrayList of student
while(rslt.next()){
std.add(new
student(rslt.getString(1),rslt.getString(2),rslt.getString(3),rslt.getString(4)));
// transfer ResultSet data into ArrayList
}
return std;
}
catch(Exception er){
return null;
}
}
Transaction Management in JDBC
 Transaction represents a single unit of work.
 The ACID properties describes the transaction management well.
ACID stands for Atomicity, Consistency, isolation and durability.

• Atomicity means either all successful or none.


• Consistency ensures bringing the database from one
consistent state to another consistent state.
• Isolation ensures that transaction is isolated from other
transaction.
• Durability means once a transaction has been committed, it
will remain so, even in the event of errors, power loss etc.

Advantage of Transaction Mangaement


fast performance It makes the performance fast because database
is hit at the time of commit.
In JDBC, Connection interface provides
methods to manage transaction.

Method Description
void It is true bydefault means
setAutoCommit(bool each transaction is
ean status) committed bydefault.

void commit() commits the transaction.

void rollback() cancels the transaction.


Example of transaction management in jdbc using
Statement
import java.sql.*;
class FetchRecords{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localho
st:1521:xe","system","oracle");
con.setAutoCommit(false);

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.

Stored Procedure Function


is used to perform business logic. is used to perform calculation.

must not have the return type. must have the return type.

may return 0 or more values. may return only one values.

We can call functions from the Procedure cannot be called from


procedure. function.
Procedure supports input and output Function supports only input
parameters. parameter.
Exception handling using try/catch Exception handling using try/catch
block can be used in stored can't be used in user defined
procedures. functions.
Stored Procedures
To call stored procedures, you invoke methods in
the CallableStatement or PreparedStatement class.
The basic steps for calling a stored procedures using
standard CallableStatement methods are:

1. Invoke the Connection.prepareCall method with the CALL


statement as its argument to create a CallableStatement object.You
can represent parameters with standard parameter markers (?) or
named parameter markers. You cannot mix named parameter
markers with standard parameter markers in the same CALL
statement.
2. Invoke the CallableStatement.setXXX methods to pass values to
the input parameters (parameters that are defined as IN or INOUT
in the CREATE PROCEDURE statement).This step assumes that you
use standard parameter markers or named parameters.
Alternatively, if you use named parameter markers, you use IBM
Data Server Driver for JDBC and SQLJ-only methods to pass values
to the input parameters.

3. Invoke the CallableStatement.registerOutParameter method to


register parameters that are defined as OUT in the CREATE
PROCEDURE statement with specific data types.This step assumes
that you use standard parameter markers. Alternatively, if you use
named parameter markers, you use IBM Data Server Driver for
JDBC and SQLJ-only methods to register OUT parameters with
specific data types.
4. Invoke one of the following methods to call the stored procedure:

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.

6. Invoke the CallableStatement.getXXX methods to


retrieve values from the OUT parameters or INOUT
parameters.

7. Invoke the CallableStatement.close method to


close the CallableStatement object when you have
finished using that object.
Call the stored procedure using JDBC
To call the stored procedure, you need to create it in the
database. Here, we are assuming that stored procedure looks
like this

create or replace procedure "INSERTR"


(id IN NUMBER,
name IN VARCHAR2)
is
begin
insert into user420 values(id,name);
end;
/
Call the stored procedure using JDBC
To call the stored procedure, you need to create it in the
database. Here, we are assuming that stored procedure looks
like this

create or replace procedure "INSERTR"


(id IN NUMBER,
name IN VARCHAR2)
is
begin
insert into user420 values(id,name);
end;
/
create table user420(id number(10), name varchar2(200));
import java.sql.*;
public class Proc {
public static void main(String[] args) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");


stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.execute();

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();

You might also like