0% found this document useful (0 votes)
25 views49 pages

Unit 4 Part 2 Database Programming With JDBC

Jdbc

Uploaded by

SAKSHI CHAUHAN
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
25 views49 pages

Unit 4 Part 2 Database Programming With JDBC

Jdbc

Uploaded by

SAKSHI CHAUHAN
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 49

UNIT 4

Java Bean & JDBC


UNIT 4

Java Database Connectivity ( JDBC) (Part 2)


Database Programming with JDBC
• JDBC (Java Database Connectivity) is a java API to connect
and execute query with the database. JDBC API uses JDBC
drivers to connect with the database.

• The java.sql package contains classes and interfaces for


JDBC API.
Applications of JDBC
• Java Applications
• Java Applets
• Java Servlets
• Java Server Pages (JSPs)
• Enterprise JavaBeans (EJBs).
Types of JDBC drivers
There are four types of JDBC drivers:

1. JDBC-ODBC Bridge Driver/Type 1


2. Native Driver/Type 2
3. Network Protocol Driver (JDBC-Net pure Java)/
Type3
4. Thin Driver (100% Pure Java)/ Type4
JDBC-ODBC bridge driver
JDBC Driver is a software component that enables java application
to interact with the database. 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.
JDBC-ODBC bridge driver
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.
• ODBC- Open Database Connectivity. It is an open
standard application programming interface (API) for
accessing a database. By using ODBC statements in a
program, you can access files in a number of different
databases, including Access, dBase, DB2, Excel, and
Text.
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.
Native-API driver
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.
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.
Network Protocol driver
Advantage:
• No client side library is required because of application
server that can perform many tasks like auditing, load
balancing etc.

Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in the
middle tier.
• Maintenance becomes costly because it requires
database-specific coding to be done in the middle tier.
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.
Thin driver
Advantage:
• Better performance than all other drivers.
• No software is required at client side or server side.

Disadvantage:
• Drivers depend on the Database.
Steps to connect to the database in java

There are 5 Steps to connect to the database in java:

• Register the driver class


• Creating connection
• Creating statement
• Executing queries
• Closing 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. Class.forName simply loads the
mentioned class in JVM.

Syntax of forName() method

• public static void forName (String className)


throws ClassNotFoundException
Or DriverManager Class

DriverManager.registerDriver()
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 SQLException
2) public static Connection getConnection(String url,
String name,String password) throws SQLException
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


Interfaces Uses
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.
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

• executeUpdate() method is used for updating


existing records.
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 Connect Java Application with mysql database
create database EMPLOYEE;
use EMPLOYEE;
create table emp(id int(10),name varchar(40),age int(3));
import java.sql.*;
class MysqlCon
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306
/EMPLOYEE");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getInt(3));
con.close();
}
catch(Exception e)
{
System.out.println(e); 1. Register driver class
} 2. Creating connection
3. Creating statement
} 4. Executing queries
} 5. Closing connection
Delete

int result=stmt.executeUpdate("delete from emp765 where id=33");


System.out.println(result+" records affected");

Insert
prepared statement
Insert record: (Using prepared statement)

PreparedStatement stmt=con.prepareStatement("insert
into Emp values(?,?)");
stmt.setInt(1,101); //1 specifies the first parameter in query
stmt.setString(2,“ABC");

int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
Update:

PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?");

stmt.setString(1,“EMPLOYEE");//1 specifies the first parameter in the query i.e. name


stmt.setInt(2,101);

int i=stmt.executeUpdate();
System.out.println(i+" records updated");
Interfaces Uses
Statement Used for general-purpose access to your database. Useful
when you are using static SQL statements at runtime. The
Statement interface cannot accept parameters.
PreparedStatement Used when you plan to use the SQL statements many
times. The PreparedStatement interface accepts input
parameters at runtime.
CallableStatement Used when you want to access the database stored
procedures. The CallableStatement interface can also
accept runtime input parameters.
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 Management

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 setAutoCommit (boolean It is true bydefault means each transaction is
status) committed bydefault.

void commit() commits the transaction.

void rollback() cancels the transaction.

void setSavepoint() used to create a new savepoint

void releaseSavepoint() remove/release a savepoint using releaseSavepoint


() method.
import java.sql.*;
class FetchRecords
{
public static void main(String args[])throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(“("jdbc:mysql://localhost
:3306/EMPLOYEE","root","root”);
con.setAutoCommit(false);

Statement stmt=con.createStatement();
stmt.executeUpdate("insert into emp values(190,'abhi',40000)");
stmt.executeUpdate("insert into emp values(191,'umesh',50000)");

con.commit();
con.close();
}
JDBC - Stored Procedure
Java CallableStatement Interface

• CallableStatement interface is used to call the stored


procedures and functions.

• We can have business logic on the database by the


use of stored procedures and functions that will
make the performance better because these are
precompiled.
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.
• Three types of parameters exist − IN, OUT, and INOUT. The
PreparedStatement object only uses the IN parameter. The
CallableStatement object can use all the three.

• Here are the definitions of each −

Parameter Description
A parameter whose value is unknown when the SQL
IN statement is created. You bind values to IN parameters
with the setXXX() methods.

A parameter whose value is supplied by the SQL


OUT statement it returns. You retrieve values from the OUT
parameters with the getXXX() methods.

A parameter that provides both input and output values.


INOUT You bind variables with the setXXX() methods and
retrieve values with the getXXX() methods.
The prepareCall() method of Connection interface returns
the instance of CallableStatement. Syntax is given below:

• public CallableStatement prepareCall("{ call proceduren


ame(?,?...?)}");

Example:

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


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

Let's create the simple function in the database first.

create or replace function sum4


(n1 in number,n2 in number)
return number
is
temp number(8);
begin
temp :=n1+n2;
return temp;
end;
/
import java.sql.*;

public class FuncSum {


public static void main(String[] args) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(" jdbc:mysql://localhost:
3306 /EMPLOYEE ","system",“sqll");

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


stmt.setInt(2,10);
stmt.setInt(3,43);
stmt.registerOutParameter(1,Types.INTEGER);
stmt.execute();

System.out.println(stmt.getInt(1));
}
}
What are the major components of the JDBC?

• DriverManager, Driver, Connection, Statement, and


ResultSet
• DriverManager, Driver, Connection, and Statement
• DriverManager, Statement, and ResultSet
• DriverManager, Connection, Statement, and
ResultSet
Select the packages in which JDBC classes are defined?

• jdbc and javax.jdbc


• rdb and javax.rdb
• jdbc and java.jdbc.sql
• sql and javax.sql
Thin driver is also known as?

• Type 3 Driver
• Type-2 Driver
• Type-4 Driver
• Type-1 Driver
What is the correct sequence to create a database connection?

i. Import JDBC packages.


ii. Open a connection to the database.
iii. Load and register the JDBC driver.
iv. Execute the statement object and return a query resultset.
v. Create a statement object to perform a query.
vi. Close the resultset and statement objects.
vii. Process the resultset.
viii. Close the connection.

i, ii, iii, v, iv, vii, viii, vi


i, iii, ii, v, iv, vii, vi, viii
ii, i, iii, iv, viii, vii, v, vi
i, iii, ii, iv, v, vi, vii, viii
Which of the following method is used to perform DML
statements in JDBC?

• executeResult()
• executeQuery()
• executeUpdate()
• execute()
Which methods are required to load a database driver
in JDBC?

• getConnection()
• registerDriver()
• forName()
• Both b and c
Which of the following is not a valid statement in JDBC?

• Statement
• PreparedStatement
• QueryStatement
• CallableStatement
What does setAutoCommit(false) do?

• It will not commit transactions automatically after


each query.
• It explicitly commits the transaction.
• It never commits the transactions.
• It does not commit transaction automatically after
each query

You might also like