Sapna Saxena: Presented by

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 49

Presented By:

Sapna Saxena
Lecturer, CSE Department
Chitkara University
Introduction
A RDBMS is usually the primary data resource in
an enterprise application.
The JDBC API provides developers with a way to
connect to relational data from within Java code.
Using the JDBC API, developer can create a client
that can connect to a database, execute SQL
statements, and processes the result of those
statements.
Introduction
JDBC helps you to write java applications that
manage these three programming activities:
1. Connect to a data source, like a database
2. Send queries and update statements to the
database
3. Retrieve and process the results received from
the database in answer to your query
In a package called java.sql, JDBC consists of a
set of class files.
Classes of jav.sql package
java.sql.DriverManager: loads driver,
and creates connection to the database
 java.sql.Driver: represents driver
java.sql.Connection: represents a
connection to the database
java.sql.Statement: executes statements
java.sql.Resultset: holds results of
executing statements
JDBC–ODBC
The ODBC class of databases are a subset of ANSI
SQL-2 databases.
It is a standard proposed by Microsoft.
In Computing, Open Database Connectivity
(ODBC) provides a standard software API
method for using DBMSs.
The designers of ODBC aimed to make it
independent of programming languages,
database systems, and Operating systems.
JDBC–ODBC Bridge
Java soft in a join effort with Intersolv that created
an implementation of the java.sql interface which is
designed to allow access to ODBC databases in
order to get JDBC.
There is an ODBC driver for each type of database.
In addition, the application talks to a particular
database through the ODBC driver manager. The
driver manager translates between the application
and the ODBC driver and the ODBC driver
translates between the driver manager and the
particular database.
JDBC Architecture
ResultSet ResultSet ResultSet
Statement PreparedStatement CallableStatement

Connection

ODBC Driver Driver Manager ODBC Driver

JDBC – ODBC
Bridge

ODBC Driver

Oracle Sybase
Database Database
Oracle
Database
JDBC Drivers
Driver must be registered with the JDBC
DriverManager, before using Driver. This is done by
using Class.forName() method, as –

try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Class.forName(“com.oracle.jdbc.OracleDriver”);
} catch (ClassNotFoundexception ce) {
// Handle exception
}
JDBC Driver Types
There are following types of JDBC Drivers –

JDBC-ODBC Bridge plus ODBC driver


Native API, Partly – Java Driver
Pure Java driver for database Middleware
Pure Java driver for direct – to - Database
JDBC–ODBC Bridge plus an ODBC Driver
All database interaction happens via the
ODBC API in this type of driver. The JDBC
driver makes ODBC API function calls which
inturn interacts with the backend database.
This type of database is mainly dependent on
the ODBC API and requires ODBC API to be
installed on the client machine.
Native API Partly Java Driver
Java This driver
Application
converts JDBC
JDBC API calls into
JDBC Driver database-specific
Manager or SQL statements.
DataSource Object Though all DBMS
use standard SQL
JDBC-ODBC Partial Java for database
Bridge Diver JDBC Driver
interactions, all
ODBC DB Client Lib DBMS do not
DB Client Lib support all the
features.
Database Database
server server
Pure Java Driver for Database
Middleware
Net pure Java Driver converts JDBC function
calls to an intermediate function calls such as
RMI, CORBA or HTTP calls. The net protocol
in turn translates these calls into standard
function calls.
Pure Java Driver for Direct-to-
Database  A Type 4 driver
Java
Applet/Application
takes JDBC calls and
translates them into
JDBC API
the network
JDBC Driver protocol which is
Manager or
DataSource Object used directly by the
DBMS. Thus direct
Pure Java Partial Java calls can make to
JDBC Driver JDBC Driver
the DBMS server by
DB Middleware the client machines
or application
Database Database server.
server server
Type 1 Type 2
The java.sql Package
Based on the different functionality, the classes
in the java.sql package can be divided into
following categories –
Connection Management
Database Access
Data Types
Database Metadata
Exceptions and Warnings
Connection Management
Following classes / interfaces allow to establish a
connection to the database –
Java.sql.DriverManager – This class provides
functionality to manage one or more database
drivers. Each driver in turn lets you connect to a
specific database.
Java.sql.Driver – This is an interface that abstracts
the vendor specific connection protocol.
Java.sql.connection – This interface abstracts most
of the interaction with the database. Using a
connection, you can send SQL statements to the
database, and read the results of execution.
Database Access
After obtaining a connection following classes /
interfaces allow to send statements to the database –
Java.sql.Statement – This inteface lets you to execute
SQL statements over the underlying connection and
access the result.
Java.sql.PreparedStatement – This is a variant of
java.sql.Statement interface, which allows
parameterized SQL statements. Parameterized SQL
statements include parameter markers (as “?”), which
can be replaced with actual value later on.
Database Access
Java.sql.CallableStatement – This interface lets
you to execute stored procedure.
 java.sql.ResultSet – This interface abstracts the
result of SELECT statements. It also provides
methods to access the results row by row.
Data Types
With regard to Data types, the java.sql package also
provides several java data types that correspond
to some of the SQL types. These can be used to as
appropriate depending on what a field in a result
row corresponds to in the concerned database –
Java.sql.array Java.sql.Timestamp
Java.sql.Blob java.sql.Ref
Java.sql.Clob java.sql.Struct
Java.sql.Date java.sql.Types
Java.sql.Time
Database Metadata
The JDBC API also includes facilities to obtain
metadata about the database, parameters to
statements, and results –
java.sql.DatabaseMetadata – used to obtain
database features
Java.sql.ResultsetMetadata – provides methods
to access metadata of resultset, such as the
names of columns, their types, etc.
Java.sql.ParameterMetadata – allows you to
access the database type of parameters in
prepared statements.
Exceptions and Warnings
The following classes encapsulate database
access errors and warnings –
java.sql.SQLException
java.sql.SQLWarning
java.sql.BatchUpdateException
Java.sql.DataTruncation
Basic steps to use a database in
Java
1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections
1.Establish a connection
Remember, The loading of the database driver
does not connect to the database; but it merely
creates an environment in the program where
this can be done.
Prior to any database specific SQL statements
can be executed, the requirement is, a
connection must be established to the database.
This can accomplished through a call to the
DriverManager getConnection method to find a
specific driver that can create a connection to the
URL requested.
1.Establish a connection
import java.sql.*;
Load the vendor specific driver
 Class.forName("oracle.jdbc.driver.OracleDriver");
 Dynamically loads a driver class, for Oracle database

The first step in using JDBC is to load the JDBC-


ODBC bridge driver.
This is usually accomplished by the forName static
method of the Class object which is the part of
base Java system.
1.Establish a connection
Make the connection
 Connection con =
DriverManager.getConnection( "jdbc:oracle:thin:@ora
cle-prod:1521:OPROD", username, passwd);

The loading of JDBC driver does not connect to the


database, but it creates the environment where it
can be done.
Here, the DriverManager searches through
registered drivers until the required one is found
whose URL is provided.
2. Create JDBC statement(s)
In order to interact with the database, the SQL
statement must be executed. This requires that a
Statement object needs to be created to manage
the SQL statements. This is accomplished with a
call to the Connection class createStatement
method.
2. Create JDBC statement(s)
Statement stmt =
con.createStatement() ;

In the above call, it creates a Statement object


using the established database connection.
The Statement class provides methods for
executing SQL statements and retrieving the
results from the statement execution.
3. Executing SQL Statements
String createStudent = "Create table Student " +
"(SSN Integer not null, Name VARCHAR(32), " +
"Marks Integer)";
stmt.executeUpdate(createStudent);

String insertStudent = "Insert into Student values“


+ "(123456789,abc,100)";
stmt.executeUpdate(insertStudent);
4. Get ResultSet
The SQL calls sends the queries to the database
and returns the results of the query as a
ResultSet.
If there is an error to be generated during the
execution of the query, an exception is generated
and caught using the try – catch block.
Successful execution of the executeQuery moves
control to the next line of code.
4. Get ResultSet
String queryStudent = "select * from Student";

ResultSet rs = Stmt.executeQuery(queryStudent);
Iterate ResultSet
while (rs.next()) {
int ssn = rs.getInt("SSN");
String name = rs.getString("NAME");
int marks = rs.getInt("MARKS");
}
Close connection
stmt.close();
con.close();
import java.sql.*;
import javax.sql.*;
import java.lang.Object;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
public class Display {
public static void main(String[] args) {
Connection conn;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:sap","","");
Statement stmt = conn.createStatement();
ResultSet r = stmt.executeQuery ("SELECT * FROM emp");
while (r.next()){
System.out.println("Name : " + r.getString(1) + " " +

r.getString(2));
System.out.println("Designation : " + r.getString(3));
System.out.println("Salary : " + r.getString(4) + "\n");
}
r.close();
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println("ERROR : " + e);
e.printStackTrace(System.out);
}
}
}
Creating Table
Following table is to be created –
Employee_ID Name
6323 Hemanth
5768 Bob
1234 Shawn
5678 Michaels

CREATE TABLE Employees


(Employee_ID INTEGER,
Name VARCHAR(30));
import java.sql.*;
import javax.sql.*;
public class Display {
public static void main(String[] args) {
Connection conn;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:sap","","");
String createString = "create table Employees (" +
"Employee_ID INTEGER, " + "Name VARCHAR(30))";
Statement stmt = con.createStatement();
stmt.executeUpdate(createString);
}
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println("ERROR : " + e);
e.printStackTrace(System.out);
}
}
}
Using Prepared Statements
Sometimes it is more convenient to use a
PreparedStatement object for sending SQL
statements to the database. This special type
of statement is derived from the more general
class, Statement, that you already know.
If you want to execute a Statement object
many times, it normally reduces execution.
Using Prepared Statements
The main feature of a PreparedStatement object is
that it is given an SQL statement when it is created.
The advantage to this is that in most cases, this
SQL statement is sent to the DBMS right away,
where it is compiled.
As a result, the PreparedStatement object contains
not just an SQL statement, but an SQL statement
that has been precompiled. This means that when
the PreparedStatement is executed, the DBMS can
just run the PreparedStatement SQL statement
without having to compile it first.
Using Prepared Statements
Although PreparedStatement objects can be used
for SQL statements with no parameters, you
probably use them most often for SQL
statements that take parameters.
The advantage of using SQL statements that take
parameters is that you can use the same
statement and supply it with different values
each time you execute it.
Creating a PreparedStatement
Object
PreparedStatement updateSales =
con.prepareStatement( "UPDATE COFFEES SET
SALES = ? WHERE COF_NAME LIKE ?");

The variable updateSales now contains the SQL


statement, "UPDATE COFFEES SET SALES = ?
WHERE COF_NAME LIKE ?", which has also, in
most cases, been sent to the DBMS and been
precompiled.
Supplying Values for
PreparedStatement Parameters
You need to supply values to be used in place of the
question mark placeholders (if there are any) before
you can execute a PreparedStatement object. You do
this by calling one of the setXXX methods defined in
the PreparedStatement class. If the value you want
to substitute for a question mark is a Java int, you
call the method setInt. If the value you want to
substitute for a question mark is a Java String, you
call the method setString, and so on. In general,
there is a setXXX method for each primitive type
declared in the Java programming language.
Supplying Values for
PreparedStatement Parameters
The following line of code sets the first question
mark placeholder to a Java int with a value of 75:
updateSales.setInt(1, 75);
setXXX The first argument given to a setXXX
method indicates which question mark
placeholder is to be set, and the second argument
indicates the value to which it is to be set.
The next example sets the second placeholder
parameter to the string " Colombian":
updateSales.setString(2, "Colombian");
Supplying Values for
PreparedStatement Parameters
Therefore, the following code fragments
accomplish the updation:

PreparedStatement updateSales =
con.prepareStatement( "UPDATE COFFEES SET
SALES = ? WHERE COF_NAME LIKE ? ");
updateSales.setInt(1, 75);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate():
Using a Loop to Set Values
Looking at these examples, you might wonder why
you would choose to use a PreparedStatement object
with parameters instead of just a simple statement,
since the simple statement involves fewer steps. If
you were going to update the SALES column only
once or twice, then there would be no need to use an
SQL statement with input parameters. If you will be
updating often, on the other hand, it might be much
easier to use a PreparedStatement object, especially
in situations where you can use a for loop or while
loop to set a parameter to a succession of values.
PreparedStatement updateSales; String updateString
= "update COFFEES " + "set SALES = ? where
COF_NAME like ?";
updateSales = con.prepareStatement(updateString);
int [] salesForWeek = {175, 150, 60, 155, 90};
String [] coffees = {"Colombian", "French_Roast",
"Espresso", "Colombian_Decaf",
"French_Roast_Decaf"};
int len = coffees.length;
for(int i = 0; i < len; i++) {
updateSales.setInt(1, salesForWeek[i]);
updateSales.setString(2, coffees[i]);
updateSales.executeUpdate();
}
Stored Procedures
A stored procedure is a group of SQL statements
that form a logical unit and perform a particular
task. Stored procedures are used to encapsulate a
set of operations or queries to execute on a
database server. For example, operations on an
employee database (hire, fire, promote, lookup)
could be coded as stored procedures executed by
application code. Stored procedures can be
compiled and executed with different parameters
and results, and they may have any combination
of input, output, and input/output parameters.
Stored Procedures
In some DBMSs, the following SQL statement
creates a stored procedure:
create procedure SHOW_SUPPLIERS
as
select SUPPLIERS.SUP_NAME,
COFFEES.COF_NAME from SUPPLIERS, COFFEES
where SUPPLIERS.SUP_ID = COFFEES.SUP_ID
order by SUP_NAME
Stored Procedures
The following code puts the SQL statement into a
string and assigns it to the variable
createProcedure, which we will use later:
String createProcedure = "create procedure
SHOW_SUPPLIERS " + "as " + "select
SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " +
"from SUPPLIERS, COFFEES " + "where
SUPPLIERS.SUP_ID = COFFEES.SUP_ID " + "order
by SUP_NAME";
Calling a Stored Procedure
from JDBC
JDBC allows you to call a database stored
procedure from an application written in the Java
programming language.
The first step is to create a CallableStatement
object. As with Statement and
PreparedStatement objects, this is done with an
open Connection object.
A callableStatement object contains a call to a
stored procedure; it does not contain the stored
procedure itself.
Calling a Stored Procedure
from JDBC
The first line of code below creates a call to the stored
procedure SHOW_SUPPLIERS using the connection
con. The part that is enclosed in curly braces is the
escape syntax for stored procedures. When the driver
encounters "{call SHOW_SUPPLIERS}", it will translate
this escape syntax into the native SQL used by the
database to call the stored procedure named
SHOW_SUPPLIERS.
CallableStatement cs = con.prepareCall("{call
SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();

You might also like