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

UNIT-2-JDBC Programming-AJP-6TH-SEM-SUMMER-2024

The document discusses JDBC architecture and drivers. It explains the four types of JDBC drivers - Type 1, Type 2, Type 3, and Type 4 drivers. It also describes the five steps for JDBC connectivity - registering the driver class, creating a connection, creating a statement, executing queries, and closing the connection.

Uploaded by

mark.co0411
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)
11 views

UNIT-2-JDBC Programming-AJP-6TH-SEM-SUMMER-2024

The document discusses JDBC architecture and drivers. It explains the four types of JDBC drivers - Type 1, Type 2, Type 3, and Type 4 drivers. It also describes the five steps for JDBC connectivity - registering the driver class, creating a connection, creating a statement, executing queries, and closing the connection.

Uploaded by

mark.co0411
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/ 20

BHAGWAN MAHAVIR UNIVERSITY

FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

UNIT-2: JDBC Programming

Que:1: Explain JDBC Architecture with diagram.

 Java Application
It is a java applet or a servlet that communicates with a data source.
 JDBC API
The JDBC API allows Java programs to execute SQL statements and retrieve results.
Some of the important classes and interfaces defined in JDBC API
 Driver Manager
It plays an important role in the JDBC architecture. It uses some database-specific
drivers to effectively connect enterprise applications to databases.
 JDBC Driver
To communicate with a data source through JDBC, you need a JDBC driver that
intelligently communicates with the respective data source.

Advanced Java Programming – Theory (1010206604) Page 1 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Que:2: Explain JDBC Drivers with diagram.


 JDBC drivers are client-side adapters (installed on the client machine, not on the
server) that convert requests from Java programs to a protocol that the DBMS can
understand.
 JDBC drivers are the software components which implements interfaces in JDBC
APIs to enable java application to interact with the database.
 There are four types of JDBC drivers defined by Sun Microsystem that are mentioned
below:

1. Type-1 driver or JDBC-ODBC bridge driver


2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver

(1) Type-1 OR JDBC-ODBC bridge driver:


 Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the
database.
 ODBC must be set up on every client machine.
 The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC
function calls.
 Type-1 driver is also called Universal driver because it can be used to connect to any
of the databases.
 E.g. MS Access

Advanced Java Programming – Theory (1010206604) Page 2 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Advantages:
o easy to use.
o can be easily connected to any database.

Disadvantages:
o Due to large number of translations, execution speed is decreased.
o Dependent on the ODBC driver.
o The ODBC driver needs to be installed on the client machine.

(2) Type-2 OR 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.
 E.g. Oracle OCI driver, Weblogic OCI driver, Type2 for Sybase

Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
o it may be considerably faster than a Type 1 driver.

Advanced Java Programming – Theory (1010206604) Page 3 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.
o This driver is platform dependent.

(3) Type-3 OR 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.
 Pure Java Driver
 Depends on Middleware server
 Follows a three-tier communication approach.
 E.g.: IDS Driver, Weblogic RMI Driver

Advantage:
o No client side library is required because of application server that can perform many tasks
o Since the communication between client and the middleware server is database
independent, there is no need for the database vendor library on the client.
o We can switch from one database to other without changing the client-side driver class,
by just changing configurations of middleware server.

Advanced Java Programming – Theory (1010206604) Page 4 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-specific
coding to be done in the middle tier.
o Compared to Type 2 drivers, Type 3 drivers are slow due to increased number of network
calls.

(4) Type-4 OR 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.
 This kind of driver is extremely flexible, you don't need to install special software
on the client or server.

Advanced Java Programming – Theory (1010206604) Page 5 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
o Completely implemented in Java to achieve platform independence.
o No native libraries are required to be installed in client machine.

Disadvantage:
o Drivers depend on the Database.

Que:3: Explain JDBC Connectivity Steps.


5 steps to connect any java application with database in java using JDBC.
 Register the driver class
 Creating connection
 Creating statement
 Executing queries
 Closing connection

 Register the driver class


• forName() method of class Class used to register the driver class
• Syntax:
• public static void forName(String classname) throws ClassNotFoundException
• Example:
• class.forName(“com.mysql.jdbc.Driver”);

 Creating connection
• getConnection() method of DriverManager class is used to establish connection with
the database
• Syntax
• public static Connection getConnection(String url) throws SQLException
• public static Connection getConnection(String url, String name, String password)
throws SQLException
• Example:
Connection c=DriverManager.getConnection(jdbc:mysql://localhost:3306/db”,”root”,””);

Advanced Java Programming – Theory (1010206604) Page 6 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

 Creating statement
• CreateStatement() method of Connection interface is used to create statement
• Object of statement is responsible to execute queries with database
• Syntax:
• public Statement createStatement() throws SQLException
• Example:
Statement st=con.createStatement();

 Executing queries
• executeQuery() method of Statement interface is used to execute queries to the db
• executeUpdate() method for insert.update,delete query
 Syntax:
• public ResultSet executeQuery(String sql)throws SQLException
 Example:
ResultSet rs=st.executeQuery(“select * from stud”);
while(rs.next())
{
System.out.println(rs.getInt(1)+””+rs.getString(2));
}

 Closing connection
• Close() method of Connection interface is used to close the connection
• Statement & ResultSet will be closed automatically by closing connection object
• Syntax:
• public void close() throws SQLException
• Example:
con.close()

Advanced Java Programming – Theory (1010206604) Page 7 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Que:4: What is Statement in JDBC ? How many types of Statement in


JDBC?Explain each types in detail.

 The statement interface is used to create SQL basic statements in Java.


 It provides methods to execute queries with the database.
 There are different types of statements that are used in JDBC as follows:
1. Create Statement
2. Prepared Statement
3. Callable Statement

1. createStatement :
 From the connection interface, you can create the object for this interface.
 It is generally used for general–purpose access to databases and is useful while using
static SQL statements at runtime.
 createStatement() method is used with con object of Connection interface.
 Syntax:
Statement statement = connection.createStatement();
 Example:
Statement st=con.createStatement();
 Once the Statement object is created, there are three ways to execute it.
o Using execute()
o Using executeUpdate()
 Executes the query.
 It is used for create, drop, insert, update, delete etc.
o Using executeQuery()
 Executes the select query.
 It returns an instance of ResultSet.

Advanced Java Programming – Theory (1010206604) Page 8 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

2. PreparedStatement:
 It is used when you plan to use the SQL statements multiple times.
 The PreparedStatement interface accepts input parameters at runtime.
 In this, “?” is used instead of the parameter, if you can pass the parameter dynamically
by using the methods of PREPARED STATEMENT at run time.
 Example
// Step: to Create a statement
PreparedStatement ps = con.prepareStatement(
" insert into student values(?,?,?)");
// Step: to Execute the query
ps.setString(1, "1423"); //Enr_no
ps.setString(2, "abc"); //Name
ps.setString(3, "computer"); //Branch
ps.executeUpdate();

 Methods of PreparedStatement:

Method name Description


public void Sets the integer value to the
setInt(int paramIndex, int value) given parameter index.

public void Sets the String value to the


setString(int paramIndex, String given parameter index.
value)
public void Sets the float value to the given
setFloat(int paramIndex, float value) parameter index.

public void Sets the double value to the


setDouble(int paramIndex, double given parameter index.
value)
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.

Advanced Java Programming – Theory (1010206604) Page 9 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

3. CallableStatement:
 The Callable Statement interface provided by JDBC API helps in executing stored
procedures.
 CallableStatement interface is used to call the stored procedures.
 Suppose you need to get the age of student based on the date of birth, you may
create a procedure that receives date as the input and returns age of the student as
the output.
 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.

Parameter name Description


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

OUT A parameter whose value is supplied by the


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

INOUT A parameter that provides both input and


output values. You bind variables with the
setXXX() methods and retrieve values with
the getXXX() methods.

Advanced Java Programming – Theory (1010206604) Page 10 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

 Syntax:
CallableStatement cstmt = con.prepareCall("{call Procedure_name(?, ?}");
 Example
CallableStatement cs=conn.prepareCall("{call getage(?,?)}");
cs.setString(1,”08-10-1990”);
cs.registerOutParameter(2,Types.VARCHAR);
cs.execute();
System.out.println(cs.getString(2));
cs.close();

Que:5: What is ResultSet interface in JDBC? Explain with various


methods for ResultSet in JDBC.

 The term "result set" refers to the row and column data contained in a ResultSet object.
 A ResultSet object maintains a cursor that points to the current row in the result set.
 The SELECT statement is the standard way to select rows from a database and view
them in a result set.
 The java.sql.ResultSet interface represents the result set of a database query.
 The methods of the ResultSet interface divide into three categories

Method name Description


Navigational method Used to move the cursor around.

Get method Used to view the data in the columns


of the current row being pointed by
the cursor.
Update method Used to update the data in the columns of
the current row. The updates can then be
updated in the underlying database as
well.

Advanced Java Programming – Theory (1010206604) Page 11 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Navigational method of ResultSet:

Method name Description


boolean first() Moves the cursor to the first row.
throws SQLException

boolean last() Moves the cursor to the last row.


throws SQLException

boolean next() Moves the cursor to the next row. This


throws SQL Exception method returns false if there are no more
rows in the result set.

boolean previous() Moves the cursor to the previous row.


throws SQLException This method returns false if the previous
row is off the result set.

boolean absolute(int row) Moves the cursor to the specified row.


throws SQLException

boolean relative(int row) Moves the cursor the given number of


throws SQLException rows forward or backward, from where it
is currently pointing.
int getRow() Returns the row number that the cursor is
throws SQLException pointing to.

Get method of ResultSet:

Method name Description


int getInt(String columnName) Returns the int in the current row in
throws SQLException the column named columnName.

int getInt(int columnIndex) Returns the int in the current row in


throws SQLException the specified column index. The
column index starts at 1, meaning the

Advanced Java Programming – Theory (1010206604) Page 12 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

first column of a row is 1, the second


column of a row is 2, and so on.

String getString(String Retrieves the value of the designated


columnLabel) column in the current row of
throws SQLException this ResultSet object as a String in the
Java programming language.

String getString(int Retrieves the value of the designated


columnIndex) column in the current row of
throws SQLException this ResultSet object as a String in the
Java programming language.

Update method of ResultSet:

Method name Description


void updateString(int Changes the String in the specified
col_Index, String s) throws column to the value of s.
SQLException

void updateInt(int col_Index, Updates the designated column with


int x) an int value.
throws SQLException

void updateFloat(int Updates the designated column with


col_Index, float x) a float value.
throws SQLException

void updateDouble(int Updates the designated column with


col_Index,double x) throws a double value.
SQLException

Advanced Java Programming – Theory (1010206604) Page 13 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Que:6: List out the types and concurrency of ResultSet interface with
example in JDBC.

Types of ResultSet interface:

Method Description

ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the


result set.

ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and


backward, and the result set is not
sensitive to changes made by others to the
database that occur after the result set was
created.

ResultSet.TYPE_SCROLL_SENSITIVE The cursor can scroll forward and


backward, and the result set is sensitive to
changes made by others to the database
that occur after the result set was created.

Concurency of ResultSet:
Method Description

ResultSet.CONCUR_READ_ONLY Creates a read-only result set.

ResultSet.CONCUR_UPDATABLE Creates an updateable result set.

Advanced Java Programming – Theory (1010206604) Page 14 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Example:
try {
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex)
{
....
}

Que:7: What is ResultSetMetaData interface in JDBC?

 The metadata means data about data i.e. we can get further information from the data.
 If you have to get metadata of a table like total number of column, column name, column type
etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from
the ResultSet object.
 Methods of ResultSetMetaData interfaces are shown in table:

Method Description

getColumnCount() Retrieves the number of columns in the current ResultSet


object.

getColumnLabel() Retrieves the suggested name of the column for use.

getColumnName() Retrieves the name of the column.

getTableName() Retrieves the name of the table.

 Example:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

Advanced Java Programming – Theory (1010206604) Page 15 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

public class ResultSetMetadataExample {


public static void main(String args[]) throws Exception {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/TestDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating a Statement object
Statement stmt = con.createStatement();
//Retrieving the data
ResultSet rs = stmt.executeQuery("select * from Stud");
ResultSetMetaData rsMetaData = rs.getMetaData();
//Number of columns
System.out.println("Number of columns: "+rsMetaData.getColumnCount());
//Column label
System.out.println("Column Label: "+rsMetaData.getColumnLabel(1));
//Column name
System.out.println("Column Name: "+rsMetaData.getColumnName(1));
//Number of columns
System.out.println("Table Name: "+rsMetaData.getTableName(1));
}
}

Que:8: What is DatabaseMetaData interface in JDBC explain with


example.

• DatabaseMetaData interface provides methods to get meta data of a database such as


1. database product name,
2. database product version,
3. driver name,
4. name of total number of tables etc.

 Example:

Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bmu","root","root");

DatabaseMetaData dbmd=con.getMetaData();

Advanced Java Programming – Theory (1010206604) Page 16 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

System.out.println("getDatabaseProductName:“ +dbmd.getDatabaseProductName());

System.out.println("getDatabaseProductVersion():“ +dbmd.getDatabaseProductVersion());

System.out.println("getDriverName():"+dbmd.getDriverName());

System.out.println("getDriverVersion():“ +dbmd.getDriverVersion());

System.out.println("getURL():"+dbmd.getURL());

System.out.println("getUserName():"+dbmd.getUserName());

Que:9: How to execute SQLupdate explain with example.

 Example:

import java.sql.*;

class UpdateDemo{

public static void main(String args[]){

try{ Class.forName("com.mysql.jdbc.Driver");

Connection

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bmu","root","root");

Statement stmt=con.createStatement();

String query="update diet set Name='abc1' where Enrollno=101";

stmt.executeUpdate(query);

stmt.close();

con.close();

}catch(Exception e){ System.out.println(e);}

Advanced Java Programming – Theory (1010206604) Page 17 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Que:10: Explain transaction management with example and method.

• In JDBC, Connection interface provides methods to manage transaction.


• Methods by Connection interface displayed in a given table are:

Method Description

void setAutoCommit(boolean It is true by default, means each transaction is


status) committed bydefault.

void commit() commits the transaction.

void rollback() cancels the transaction.

Advanced Java Programming – Theory (1010206604) Page 18 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

 Example:

import java.sql.*;

class RollbackDemo{

public static void main(String args[]){

try{ Class.forName("com.mysql.jdbc.Driver");

Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bmu","root","root");

con.setAutoCommit(false);

Statement stmt=con.createStatement();

int i=stmt.executeUpdate("insert into stud values(103,'ghi',‘EC')");

con.commit(); //Commit Transaction

stmt.executeUpdate("insert into stud values(104,'mno',‘IT')");

con.rollback(); //Rollback Transaction

con.close();

}catch(Exception e){ System.out.println(e);}

Advanced Java Programming – Theory (1010206604) Page 19 of 20


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Advanced Java Programming – Theory (1010206604) Page 20 of 20

You might also like