0% found this document useful (0 votes)
10 views19 pages

Module 5 21CS32

The document provides an overview of Java Database Connectivity (JDBC), detailing its purpose, types of JDBC drivers, and the process of connecting to a database using JDBC. It outlines the steps involved in loading the JDBC driver, establishing a connection, executing SQL statements, processing results, and managing connections. Additionally, it discusses various JDBC objects such as Statement, PreparedStatement, and CallableStatement, along with example code snippets for database operations.

Uploaded by

Srisaila Nath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views19 pages

Module 5 21CS32

The document provides an overview of Java Database Connectivity (JDBC), detailing its purpose, types of JDBC drivers, and the process of connecting to a database using JDBC. It outlines the steps involved in loading the JDBC driver, establishing a connection, executing SQL statements, processing results, and managing connections. Additionally, it discusses various JDBC objects such as Statement, PreparedStatement, and CallableStatement, along with example code snippets for database operations.

Uploaded by

Srisaila Nath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Object Oriented Programming using JAVA -21CS32

Module -5

JDBC Objects

The Concept of JDBC:


• Java was not considered industrial strength programming language since java was
unable to access the DBMS.
• Each DBMS has its own way to access the data storage. low level code required to
access oracle data storage need to be rewritten to access db2.
• JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language
and awide range of databases
JDBC drivers has to do the following
 Open connection between DBMS and J2EE environment.
 Translate low level equivalents of sql statements sent by J2EE component into messages
that can be processed by the DBMS.
 Return the data that conforms to JDBC specifications to the JDBCdriver
 Return the error messages that conforms to JDBC specifications tothe JDBC driver
 Provides transaction management routines that conforms to JDBC specifications to the
JDBC driver
 Close connection between the DBMS and the J2EE component.

Figure 5.1: JAVA Architecture

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 1


Object Oriented Programming using JAVA -21CS32
JDBC Driver Types
Type 1 driver JDBC to ODBC Driver

1. It is also called JDBC/ODBC Bridge, developed by MicroSoft.


2. It receives messages from a J2EE component that conforms to the JDBC
specifications
3. Then it translates into the messages understood by the DBMS.
4. This is DBMS independent database program that is ODBC open database
connectivity.

Type 2 JAVA / Native Code Driver


1. Generates platform specific code that is code understood by platform specific code
only understood by specific databases.
2. Manufacturer of DBMS provides both java/ Native code driver.
3. Using this provides lost of portability of code.
4. It won’t work for another DBMS manufacturer

Type 3 JDBC Driver


1. Most commonly used JDBC driver.
2. Coverts SQL queries into JDBC Formatted statements.
3. Then JDBC Formatted statements are translated into the format required by the DBMS.
4. Referred as Java protocol

Type 4 JDBC Driver


1. Referred as Type 4 database protocol
2. SQL statements are transferred into the format required by the DBMS.
3. This is the fastest communication protocol.

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 2


Object Oriented Programming using JAVA -21CS32
JDBC Packages

JDBC API contains two packages. First package is called java.sql, second package is called
javax.sql which extends java.sql for advanced JDBC features.

Steps of JDBC process


1. Loading the JDBC driver
 The jdbc driver must be loaded before the J2EE component can be connected to the
database.
 Driver is loaded by calling the method and passing it the name of driver

Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”);

Or

Class.forName("oracle.jdbc.driver.OracleDriver");

2. Connecting to the DBMS.


 Once the driver is loaded, J2EE component must connect to the DBMS using
DriverManager.getConnection() method.
 It is highest class in hierarchy and is responsible for managing driver information.
 It takes three arguments URL, User, Password
 It returns connection interface that is used throughout the process to reference a database

import java.sql.*;
public class Test{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@
localhost:1521:","system","MANAGER");

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 3


Object Oriented Programming using JAVA -21CS32
3. Creating and Executing a statement
 The next step after the JDBC is loaded and connection is successfully made with a
particular database managed by the dbms, is to end a particular query to the DBMS for
processing.
 SQL query consists series of SQL command that direct DBMS to do something example
Return rows.
Connect.createStatement() method is used to create a statement Object.

 The statement object is then used to execute a query and return result object that contain
response from the DBMS

Statement DataRequest;
ResultSet Results;
try {
String query=“select * from Customers”;
DataRequest=Database.createStatement();
Results= DataRequest.executeQuery(query);
}

4. Processing data returned by the DBMS


 java.sql.ResultSet object is assigned the result received from the DBMS after the
query is processed.
 java.sql.ResultSet contain method to interact with data that is returned by the
DBMS to the J2EE Component.

Results= DataRequest.executeQuery(query);
do
{
Fname=Results.getString(Fname)
}
while(Results.next())

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 4


Object Oriented Programming using JAVA -21CS32
 In the above code it returns result from the query and executes the query. And getString
is used to process the String retrived from the database.

5. Terminating the connection with the DBMS


 To terminate the connection Database.close() method is used.

Database Connection
1. After the JDBC driver is successfully loaded and registered, the J2EE component must
connect to the database. The database must be associated with the JDBC driver.
2. The datasource that JDBC component will connect to is identified using the URL format.
The URL consists of three format.
 These are jdbc which indicate jdbc protocol is used to read the URL.
 <subprotocol> which is JDBC driver name.
 <subname> which is the name of database.
3. Connection to the database is achieved by using one of three getConnection()
methods. It returns connection object otherwise returns SQLException
4. Three getConnection() method
 getConnection(String url)
 getConnection(String url, String pass, String user)
 getConnection(String url, Properties prop)

5. getConnection(String url)
Sometimes the DBMS grant access to a database to anyone that time J2EE component
uses getConnection(url) method is used.

try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Db=DriverManager.getConnection(“jdbc:oracle:thin:@
localhost:1521:”);
}

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 5


Object Oriented Programming using JAVA -21CS32
a) getConnection(String url, String pass, String user)
Database has limited access to the database to authorized user and require J2EE to
supply user id and password with request access to the database. The method used here is.
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Db=DriverManager.getConnection(jdbc:oracle:thin:@
localhost:1521:","system","MANAGER");
}

b) getConnection(String url, Properties prop)


There might be occasions when a DBMS require information besides userid and password
before DBMS grant access to the database. This additional information is called properties and
that must be associated with Properties object. The property is stored in text file. And then
loaded by load method of Properties class.
Connection db;
Properties props = new Properties();
try
{
FileInputStream inputfile=new FileInputStream(“text.txt”);
Prop.load(inputfile);
}

Timeout
Competition to use the same database is a common occurrence in the J2EE environment
and can lead to performance degradation of J2EE application. Database may not connect
immediately delayed response because database may not available. Rather than delayed waiting
timeJ2EE component can stop connection. After some time. This time can bet set with the
following method:
DriverManager.setLoginTimeout(int sec)
return the current timeout in seconds.

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 6


Object Oriented Programming using JAVA -21CS32

Connection Pool
 Client needs frequent that needs to frequently interact with database must either open
connection and leave open connection during processing or open or close and reconnect
each time.
 Leaving the connection may open might prevent another client from accessing the
database when DBS have limited no of connections. Connecting and reconnecting is time
consuming.
 The release of JDBC 2.1 Standard extension API introduced concept on connection
pooling
 A connection pool is a collection of database connection that are opened and loaded into
memory so these connections can be reused without reconnecting to the database.
 DataSource interface to connect to the connection pool. connection pool is implemented
in application server.
 There are two types of connection to the database 1.) Logical 2.) Physical
The following is code to connect to connection pool.
Context ctext= new IntialContext()
DataSource pool =(DataSource)
ctext.lookup(“java:comp/env/jdbc/pool”);
Connection db=pool.getConnection();

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 7


Object Oriented Programming using JAVA -21CS32
Statement Object
 Statement object executes query immediately without precompiling.
 The statement object contains the excuteQuery() method , which accept query as
argument then query is transmitted for processing.
 It returns ResultSet as object.
 Another method is used when DML and DDL operations are used for processing query is
executeUpdate(). This returns no of rows as integer.
Example Program
import java.sql.*;
public class Test{
public static void main(String args[])
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:","system","MANAGER");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select *from Employee");
while(rs.next())
{
System.out.println(rs.getInt(1)+""+rs.getString(2)+"
"+rs.getString(3));
}
con.close();
}catch(SQLException e){ System.out.println(e);}
}
}

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 8


Object Oriented Programming using JAVA -21CS32
PreparedStatement Object
 A SQL query must be compiled before the DBMS processes the query.
 Compiling occurs after one of the Statement object’s execution method is called.
 Compiling a query is an overhead that is acceptable if the query is called once.
 However, the compiling process can become an expensive overhead if the query is
executed several times by the same instance of the J2EE component during the same
session
 A SQL query can be precompiled and executed by using the PreparedStatement object.

Example Program
import java.sql.*;
public class Test{
public static void main(String args[])
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:","system","MANAGER");
String query=”SELECT * FROM Customers where CustName = ?”;
PreparedStatement ps = Db.preparedStatement(query);
ps.setString(1,”123”);
ResultSet rs = ps.executeQuery(query);
}
Con.close();
catch(SQLException e)
{
System.err.println(e);
System.exit(1);
}

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 9


Object Oriented Programming using JAVA -21CS32

CallableStatement Object
 The callableStatement object is used to call a stored procedure from within J2EE object. A
stored procedure is block of code and is identified by unique name. the code can bewritten in
PL/SQL.
 Stored procedure is executed by invoking by the name of procedure.
 The callableStatement uses three types of parameter when calling stored procedure. The
parameters are IN ,OUT,INOUT.
 IN parameter contains data that needs to be passed to the stored procedure whose value is
assigned using setx() method.
 OUT parameter contains value returned by stored procedure. The OUT parameter should be
registers by using registerOutParameter() method and then later retrieved by the J2EE
component using getx() method.
 INOUT parameter is used to both pass information to the stored procedure and retrieve the
information from the procedure.

import java.sql.*;
public class Test{
public static void main(String args[])
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:","system","MANAGER");

String query=” {CALL LastOrderNumber(?)}”;


CallableStatement cs = Db.prepareCall(query);
ps.registerOutParameter(1,Types.VARCHAR);
cs.execute();

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 10


Object Oriented Programming using JAVA -21CS32
LastOrderNumber = cs.getString(1);
cs.close();
}
catch(SQLException e)
{
System.err.println(e);
}

JAVA Program to insert data into the database


import java.sql.*;
import java.io.*;
import java.util.*;
class InsertTest
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:","system","1234");
//Statement Object is created.....
PreparedStatement stmt=con.prepareStatement("insert
into Employee values(?,?,?)");
Scanner sc=new Scanner(System.in);
while(true)
{
System.out.println("Enter id");
int id=sc.nextInt();

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 11


Object Oriented Programming using JAVA -21CS32
System.out.println("Enter name:");
String n=sc.next();
System.out.println("Enter Address:");
String j=sc.next();

stmt.setInt(1,id);
stmt.setString(2,n);
stmt.setString(3,j);

stmt.executeUpdate();
System.out.println("Want to insert more data
Yes/No");
String ans=sc.next();
//if user say no then insertion of data
stopped...
if(ans.equalsIgnoreCase("No"))
break;
}
//Connection is closed.....
con.close();
System.out.println("Successfully saved .....");
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 12


Object Oriented Programming using JAVA -21CS32
ResultSet
 ResultSet object contain the methods that are used to copy data from ResultSet into java
collection object or variable for further processing.
 Data in the ResultSet is logically organized into the virtual table for further processing.
Result set along with row and column it also contains meta data.
 ResultSet uses virtual cursor to point to a row of the table.
 J2EE component should use the virtual cursor to each row and the use other methods of the
ResultSet to object to interact with the data stored in column of the row.
 The virtual cursor is positioned above the first row of data when the ResultSet is returned by
executeQuery () method.
 The virtual cursor is moved to the first row with help of next() method of ResultSet
 Once virtual cursor is positioned getx() is used to return the data. Data type of data is
represented by xx. It should match with column data type.
getString(fname) …..fname is column name.
setString(1) in this 1 indicates first column selected by query.
import java.sql.*;
public class Test{
public static void main(String args[])
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:","system","MANAGER");
boolean Records = results.next();
Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select *from Employee");


while(rs.next())
{

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 13


Object Oriented Programming using JAVA -21CS32
System.out.println(rs.getInt(1)+""+rs.getString(2)+"
"+rs.getString(3));
}
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

Scrollable ResultSet
 Until the release of JDBC 2.1 API , the virtual cursor can move only in forward directions.
But today the virtual cursor can be positioned at a specific row.
 There are six methods to position the cursor at specific location in addition to next() in
scrollable result set. firs() ,last(), absolute(), relative(), previous(), and getRow().
first() position at first row.
last() position at last row.
previous() position at previous row.
absolute()… To the row specified in the absolute function
relative()………… move relative to current row. Positive and negative no can be
given.
Ex. relative(-4) … 4 position backward direction.
getRow() returns the no of current row.
There are three constants can be passed to the createStatement()
Default is TYPE_FORWARD_ONLY. Otherwise three constant can be passed to the
create statement 1.) TYPE_SCROLL_INSENSITIVE 2.) TYPE_SCROLL_SENSITIVE
3)TYPE_SCROLL makes cursor to move both direction.
INSENSITIVE makes changes made by J2EE component will not reflect. SENSITIVE means
changes by J2EE will reflect in the result set.
import java.sql.*;
public class Test{
public static void main(String args[])

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 14


Object Oriented Programming using JAVA -21CS32
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:","system","MANAGER");
boolean Records = results.next();
Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select *from Employee");


do{
Results.first();
Results.last();
Results.previous();
Results.absolute();
Results.relative(-2);

FirstName = Results.getString(1);
LastName = Results.getString(2);
printrow = FirstName + “ “ + LastName;
System.out.println (printrow);
}while( Results.next());
Con.Cloase();
}
catch(SQLException err)
{
System.err.println("Error"+error);
System.exit(1);
}
Whatever the changes making will affect only in the result set not in the table. To update in the
table have to execute the DML (update, insert, delete) statements.

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 15


Object Oriented Programming using JAVA -21CS32
Transaction Processing
 A transaction may consist of a set of SQL statements, each of which must be successfully
completed for the transaction to be completed. If one fails SQL statements successfully
completed must be rolled back.
 Transaction is not completed until the J2EE component calls the commit() method of the
connection object. All SQL statements executed prior to the call to commit() method can be
rolled back.
 Commit() method was automatically called in the program. DBMS has set AutoCommit
feature.
 If the J2EE component is processing a transaction then it has to deactivate the auto commit()
option false.
 Transaction can also be rolled back. When not happened. Db.rollback().
 A transaction may consists of many tasks, some of which no need to roll back . in such
situation we can create a savepoints, in between transactions. It was introduced in JDBC 3.0.
save points are created and then passed as parameters to rollback() methods.
 releseSavepint() is used to remove the savepoint from the transaction.

Batch Execution of transaction


 Another way to combine sql statements into a single into a single transaction and then
execute the entire transaction.
 To do this the addBatch() method of statement object. The addBatch() method receives a
SQL statement as a parameter and places the SQL statement in the batch.
 executeBatch() method is called to execute the entire batch at the same time. It returns an
array that contains no of SQL statement that execute successfully.

String query1= "UPDATE Customers SET street =‘ 5 th Main‘ "+


Where Fname=‘BoB‘;

String query2= "UPDATE Customers SET street =‘ 10 th Main‘ " +


Where Fname=‘Tom‘;

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 16


Object Oriented Programming using JAVA -21CS32

Statement DR=DB.createStatement();
DR.addBatch(query1);
DR.addBatch(query2);
int [] updated= DR.executeBatch();

Metadata
 Metadata is data about data. MetaData is accessed by using the DatabaseMetaData interface.
 This interface is used to return the meta data information about database.
 Meta data is retrieved by using getMetaData() method of connection object.
Database metadata
The method used to retrieve meta data informations are
 getDatabaseProductNAme()…returns the product name of database.
 getUserNAme() returns the username
 getURL() returns the URL of the databse.
 getSchemas() returns all the schema name
 getPrimaryKey() returns primary key
 getTables() returns names of tables in the database

ResultSet Metadata
 ResultSetMetaData rm = Result.getMeatData()
The method used to retrieve meta data information about result set are
 getColumnCount() returns the number of columns contained in result set

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 17


Object Oriented Programming using JAVA -21CS32
Data types of SQL
SQL JDBC/Java
VARCHAR java.lang.String
CHAR java.lang.String
LONGVARCHAR java.lang.String
BIT Boolean
NUMERIC java.math.BigDecimal
TINYINT Byte

SMALLINT Short
INTEGER Int
BIGINT Long
REAL Float
FLOAT Float
DOUBLE Double
VARBINARY byte[ ]
BINARY byte[ ]
DATE java.sql.Date
TIME java.sql.Time

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 18


Object Oriented Programming using JAVA -21CS32
Exceptions handling with JDBC
Exception handling allows you to handle exceptional conditions such as program-defined errors
in a controlled fashion.
 When an exception condition occurs, an exception is thrown. The term thrown means that
current program execution stops, and control is redirected to the nearest applicable catch
clause. If no applicable catch clause exists, then the program's execution ends.
 JDBC Exception handling is very similar to Java Excpetion handling but for JDBC.
 There are three kind of exception thrown by jdbc methods.
SQLException , SQLWarnings, DataTruncation SQLException
The most common exception you'll deal with is java.sql.SQLException which result in SQL
syntax errors.
getNextException() method returns details about the error.
getErrorCode() method retrieves vendor specific error codes.

SQLWarnings
it throws warnings related to connection from DBMS. getWarnings() method of connection
object retrieves t warnings. getNextWarnings() returns
subsequent warnings.

Data Truncation
Whenever data is lost due to truncation of the data value, a truncation exception is thrown.

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 19

You might also like