0% found this document useful (0 votes)
2 views43 pages

Java 5

Java

Uploaded by

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

Java 5

Java

Uploaded by

syedatasneem85
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1. Explain different steps involved in JDBC process with a code snippet.

2. List and elaborate Database Metadata Object methods


3. List and explain three kinds of exception occurred in JDBC `
4.. Mention all steps to create the association between the database and a
JDBC/ODBC bridge.
5. Explain the four types of JDBC drivers

6. Write a program to execute a database transaction.


7. Explain JDBC multitier architecture with neat diagram i.e drivers types in
detail.
8. List the various steps of JDBC process with code snippets. `
9. Write a note on Database Metadata object methods and Resultset Metadata
object methods.

10. Explain the different steps involved in JDBC with code snippets.
11. Explain the four types of JDBC driver types.
12. Write a java program to insert data into student DATABASE and retrieve
information based on particular queries (Explain update, delete, search).
13. Write a short notes on:
i) Resultset
ii) Transaction processing.

14. What is JDBC? Explain the different JDBC driver types. `10 L2 CO5`
15. What is statement object in JDBC? Explain the following statement objects
with example
(i) Prepared statement
(ii) Callablestatement `10 L2 CO5`
16. What is Connection pooling? Explain connection pooling with neat diagrams
with code snippets. `10 L2 CO5`
17. Write a note on:
(i) Transaction Processing in JDBC.
(ii) Types of Exceptions occurred in JDBC. `10 L2 CO5`

---
18. What are database drives? Explain the different JDBC driver types. `6 L2
CO5`
20. Write any two syntax of established a connection to a database. `4 L2 CO5`
21. Describe the following concepts:
(i) Scrollable Resultset.
(ii) Callable statement.
(iii) Transaction processing.
(iv) Updatable Resultset. `10 L2 CO5`
22. What is connection pooling? Explain connection pooling with code snippets.
`6 L2 CO5`
23. Explain different kinds of exceptions in Database. `4 L2 CO5`

24. What is statement object in JDBC? Explain the following statement objects
i) Callable statement object
ii) Prepare statement object `10 M L1,L2`
25. Explain transaction processing in JDBC. `6 M L2`
26. Write any two syntax of establishing a connection to database. `4 M L1`
27. Explain the four types of JDBC drivers. `10 M L2`
28. Explain connection pooling with neat diagram and code snippets. `10 M
L2,L3`

29. What are database drivers? Explain the different JDBC driver types. `10 L2
CO5`
31. Write any two syntax of established a connection to a database. `6 L2 CO5`
32. What is connection pooling? Explain connection pooling with a neat diagram
with snippets. `7 L2 CO5`
33. Describe the following concepts:
i) Callable statement
ii) Transaction processing. `7 L2 CO5`
*Key Repeated Topics in Module-5 Q9/Q10:*
1. *4 Types of JDBC Drivers* - appears in 6/7 papers
2. *Steps of JDBC process* with code - appears in 5/7 papers
3. *Connection Pooling* with diagram/code - appears in 5/7 papers
4. *Statement vs PreparedStatement vs CallableStatement* - appears in 4/7
papers
5. *Transaction Processing* - appears in 5/7 papers
6. *JDBC Exceptions* - appears in 3/7 papers
7. *DatabaseMetadata/ResultSetMetadata* - appears in 2/7 papers
1. What is statement object in JDBC? Explain the following statement objects
i) Callable statement object
ii) Prepare statement object
Statement Object in JDBC
Definition
A Statement object in JDBC is used to send SQL queries and commands from a
Java program to a database. It acts as a bridge between the Java application and
the database.
The Statement object is created using the createStatement() method of the
Connection interface.
Syntax:
Statement st = [Link]();
Uses:
 Execute SQL queries.
 Insert, update, and delete records.
 Retrieve data from the database.

Types of Statement Objects in JDBC


1. PreparedStatement Object
Definition
A PreparedStatement is a precompiled SQL statement that is executed
multiple times with different values. It improves performance and provides
security against SQL injection.
Syntax
PreparedStatement ps =
[Link]("INSERT INTO Student VALUES(?,?)");
Steps
1. Create a PreparedStatement object.
2. Set values using setter methods.
3. Execute the query.
Example
PreparedStatement ps =
[Link]("INSERT INTO Student VALUES(?,?)");

[Link](1,101);
[Link](2,"Ali");

[Link]();
Advantages
 Faster execution because SQL is precompiled.
 Prevents SQL injection attacks.
 Easy to execute the same query multiple times.
 Improves readability and efficiency.
Applications
 Data insertion.
 Data updation.
 Searching records with user inputs.

2. CallableStatement Object
Definition
A CallableStatement is used to call stored procedures and functions present in
the database.
It extends the PreparedStatement interface and allows execution of database
procedures.
Syntax
CallableStatement cs =
[Link]("{call procedure_name(?,?)}");
Steps
1. Create CallableStatement object.
2. Set input parameters.
3. Register output parameters (if any).
4. Execute the procedure.
Example
CallableStatement cs =
[Link]("{call addStudent(?,?)}");

[Link](1,101);
[Link](2,"Ali");
[Link]();
Advantages
 Executes stored procedures directly.
 Reduces network traffic.
 Improves performance.
 Supports IN, OUT, and INOUT parameters.
Applications
 Banking systems.
 Payroll systems.
 Enterprise database applications.

Comparison of PreparedStatement and CallableStatement

PreparedStatement CallableStatement

Used for precompiled SQL


Used for stored procedures
queries

Uses prepareStatement() Uses prepareCall()

Faster for stored procedure


Faster than Statement
execution

Supports parameterized Supports IN, OUT, and INOUT


queries parameters

Used for CRUD operations Used for procedure/function calls

[Link] transaction processing in jdbc


Transaction Processing in JDBC (8 Marks)
Definition
A transaction is a group of SQL statements that are executed as a single unit of
work. Either all statements are executed successfully (Commit) or none of them
are executed (Rollback).
Transaction processing ensures data consistency, integrity, and reliability in
the database.

Need for Transaction Processing


 Maintains data consistency.
 Prevents partial updates.
 Ensures data integrity during failures.
 Supports recovery from errors.
Example: In a bank transfer, money should be deducted from one account and
credited to another account together. If one operation fails, both operations must
be cancelled.

JDBC Transaction Methods


1. setAutoCommit(false)
Disables automatic committing of SQL statements.
[Link](false);
2. commit()
Saves all changes permanently to the database.
[Link]();
3. rollback()
Undoes all changes made since the last commit.
[Link]();

Example Program
Connection con = [Link](url,user,pwd);

[Link](false);

Statement st = [Link]();

[Link]("UPDATE Account SET Balance=Balance-1000 WHERE


AccNo=101");

[Link]("UPDATE Account SET Balance=Balance+1000 WHERE


AccNo=102");

[Link]();
If any error occurs:
[Link]();

Steps in Transaction Processing


1. Establish database connection.
2. Disable auto-commit mode.
3. Execute SQL statements.
4. If all statements execute successfully, call commit().
5. If an error occurs, call rollback().
6. Close the connection.

Advantages
 Ensures data integrity.
 Maintains database consistency.
 Prevents data loss.
 Supports error recovery.
 Improves reliability of database operations.

[Link] any two syntax of establishing a connection to database


Any Two Syntaxes for Establishing a Connection to Database (6 Marks)
A database connection in JDBC is established using the
[Link]() method.
1. Using URL, Username and Password
Syntax:
Connection con =
[Link](
"jdbc:mysql://localhost:3306/studentdb",
"root",
"password");
Explanation:
 jdbc:mysql://localhost:3306/studentdb → Database URL
 root → Username
 password → Password
 Returns a Connection object.

2. Using Only Database URL


Syntax:
Connection con =
[Link](
"jdbc:odbc:studentdb");
Explanation:
 Uses only the database URL.
 Suitable when authentication is not required.
 Returns a Connection object.
4.. Explain the four types of jdbc drivers
Four Types of JDBC Drivers (12 Marks)
Introduction
A JDBC Driver is a software component that enables a Java application to
communicate with a database. JDBC provides four types of drivers for
establishing database connectivity.

1. Type-1 Driver (JDBC-ODBC Bridge Driver)


Definition
This driver converts JDBC calls into ODBC calls and then communicates with the
database through the ODBC driver.
Architecture
Java Application

JDBC API

JDBC-ODBC Bridge

ODBC Driver

Database
Advantages
 Easy to use.
 Suitable for small applications.
Disadvantages
 Requires ODBC installation.
 Low performance.
 Not platform independent.

2. Type-2 Driver (Native API Driver)


Definition
This driver converts JDBC calls into database-specific native API calls.
Architecture
Java Application

JDBC API

Native API Driver

Database Native Library

Database
Advantages
 Faster than Type-1.
 Better performance.
Disadvantages
 Requires native libraries.
 Platform dependent.
 Difficult to maintain.

3. Type-3 Driver (Network Protocol Driver)


Definition
This driver converts JDBC calls into a database-independent network protocol
and sends them to a middleware server, which communicates with the database.
Architecture
Java Application

JDBC API

Network Protocol Driver

Middleware Server

Database
Advantages
 Platform independent.
 No native library required.
 Can access multiple databases.
Disadvantages
 Requires middleware server.
 Increased network overhead.

4. Type-4 Driver (Thin Driver)


Definition
This driver directly converts JDBC calls into database-specific protocol and
communicates with the database.
Architecture
Java Application

JDBC API

Type-4 Driver

Database
Advantages
 High performance.
 Platform independent.
 No middleware or native libraries required.
 Most widely used driver.
Disadvantages
 Database-specific driver required.

Comparison of JDBC Drivers

Platform Performan
Type Driver Name
Independent ce

Type-
JDBC-ODBC Bridge No Low
1

Type-
Native API Driver No Medium
2

Type- Network Protocol


Yes Good
3 Driver

Type-
Thin Driver Yes Excellent
4
[Link] connection poolling with the neat diagram and code snippet
Connection Pooling in JDBC (12 Marks)
Definition
Connection Pooling is a technique in JDBC where a pool of database
connections is created and maintained in memory. Instead of creating a new
connection every time, an existing connection is reused from the pool.
This improves the performance of database applications by reducing the time
required to establish connections.

Need for Connection Pooling


 Creating a database connection is time-consuming.
 Frequent creation and closing of connections reduces performance.
 Reusing connections improves efficiency.
 Reduces database server load.

Neat Diagram
Client Applications


┌─────────────────┐
│ Connection Pool │
└─────────────────┘
▲ ▲ ▲
│ │ │
Conn1 Conn2 Conn3
│ │ │
└──────┼──────┘

Database
Working
1. A pool of connections is created when the application starts.
2. Client requests a connection.
3. Connection is provided from the pool.
4. After use, the connection is returned to the pool instead of being closed.
5. The same connection can be reused by another client.

Code Snippet
import [Link];
import [Link];

public class ConnectionPoolDemo


{
public static void main(String args[]) throws Exception
{
BasicDataSource ds = new BasicDataSource();

[Link]("[Link]");
[Link]("jdbc:mysql://localhost:3306/studentdb");
[Link]("root");
[Link]("root");

Connection con = [Link]();

[Link]("Connection Obtained");

[Link](); // Returned to pool


}
}

Advantages of Connection Pooling


1. Improves application performance.
2. Reduces connection creation time.
3. Efficient utilization of resources.
4. Minimizes database server overhead.
5. Supports multiple users simultaneously.
6. Increases scalability of applications.

Disadvantages
1. Requires additional memory.
2. Pool management adds complexity.
3. Incorrect configuration may reduce performance.

Applications
 Web applications.
 Enterprise applications.
 Banking systems.
 E-commerce applications.
7. Explain different steps involved in jdbc process with a code snipid
Different Steps Involved in JDBC Process with Code Snippet (12
Marks)
Introduction
JDBC (Java Database Connectivity) is an API that enables Java
applications to interact with databases. The JDBC process involves a
sequence of steps to establish a connection, execute SQL queries, and
process results.

Steps Involved in JDBC Process


1. Import JDBC Packages
Import the required JDBC classes.
import [Link].*;

2. Load and Register the Driver


Load the database driver into memory.
[Link]("[Link]");

3. Establish Connection
Create a connection between Java application and database.
Connection con = [Link](
"jdbc:mysql://localhost:3306/studentdb",
"root",
"password");

4. Create Statement Object


Create a Statement object to send SQL queries.
Statement st = [Link]();

5. Execute SQL Query


Execute SQL statements using the Statement object.
ResultSet rs =
[Link]("SELECT * FROM Student");

6. Process the Result


Retrieve and display data from the ResultSet.
while([Link]())
{
[Link](
[Link](1)+" "+
[Link](2));
}

7. Close the Resources


Close ResultSet, Statement, and Connection objects.
[Link]();
[Link]();
[Link]();
Complete JDBC Program
import [Link].*;

public class JdbcDemo


{
public static void main(String args[])
{
try
{
[Link]("[Link]");

Connection con =
[Link](
"jdbc:mysql://localhost:3306/studentdb",
"root",
"password");

Statement st =
[Link]();

ResultSet rs =
[Link](
"SELECT * FROM Student");

while([Link]())
{
[Link](
[Link](1)+" "+
[Link](2));
}

[Link]();
[Link]();
[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}

JDBC Architecture Flow


Java Application

JDBC API

JDBC Driver

Database
Advantages of JDBC
 Platform independent.
 Supports multiple databases.
 Easy database connectivity.
 Provides secure access to data.
 Supports transaction processing.

[Link] an elaborate database metadata object methods for 6 marks


DatabaseMetaData Object Methods (6 Marks)
Definition
DatabaseMetaData is an interface in JDBC that provides information
about the database, driver, tables, supported features, and database
capabilities.
It is obtained using:
DatabaseMetaData dbmd = [Link]();

Important DatabaseMetaData Methods

Method Description

getDatabaseProductNam
Returns the database name.
e()

getDatabaseProductVersi
Returns the database version.
on()

getDriverName() Returns the JDBC driver name.

getDriverVersion() Returns the JDBC driver version.

getUserName() Returns the current user name.

getURL() Returns the database URL.

Returns information about database


getTables()
tables.

Checks whether transactions are


supportsTransactions()
supported.

Checks whether batch updates are


supportsBatchUpdates()
supported.

Returns the maximum number of


getMaxConnections()
connections supported.

Example
Connection con = [Link](url,user,pwd);

DatabaseMetaData dbmd = [Link]();

[Link]("Database Name: "


+ [Link]());

[Link]("Driver Name: "


+ [Link]());

Uses of DatabaseMetaData
 Retrieves database information.
 Retrieves driver information.
 Checks database capabilities.
 Obtains table and column details.
 Helps in database administration and maintenance.

8. List and explain three kinds of exception occur in jdbc for 6 marks
Three Kinds of Exceptions Occurring in JDBC (6 Marks)
Definition
An exception is an error that occurs during the execution of a JDBC
program. JDBC provides exception classes to identify and handle database-
related errors.

1. SQLException
Definition
SQLException occurs when there is an error while accessing the database
or executing SQL statements.
Example
Connection con =
[Link]("wrong_url");
Causes
 Incorrect database URL.
 Invalid SQL query.
 Database connection failure.

2. SQLWarning
Definition
SQLWarning is not a serious error. It indicates a database access warning
that does not stop program execution.
Example
SQLWarning warning = [Link]();
Causes
 Use of deprecated database features.
 Data truncation warnings.
 Minor database issues.

3. BatchUpdateException
Definition
BatchUpdateException occurs when an error happens during the execution
of a batch of SQL statements.
Example
Statement st = [Link]();
[Link]("INSERT INTO Student VALUES(1,'A')");
[Link]("Wrong SQL Statement");
[Link]();
Causes
 Invalid SQL statement in a batch.
 Constraint violation during batch execution.

9. Mention all steps to create the association between the database and
jdbc / Odbc bridge
Steps to Create Association Between Database and JDBC–ODBC
Bridge (15 Marks)
Introduction
The JDBC–ODBC Bridge Driver (Type-1 Driver) is used to connect a
Java application to a database through the ODBC driver. To establish
communication, a Data Source Name (DSN) must be created and linked
with the database.

Steps to Create Association Between Database and JDBC–ODBC


Bridge
1. Create the Database
 Open a DBMS such as MS Access.
 Create a new database.
 Create the required tables and save the database.
Example:
Database Name : StudentDB
Table Name : Student

2. Open ODBC Data Source Administrator


 Open Control Panel.
 Select Administrative Tools.
 Click ODBC Data Source Administrator.
OR
 Press Windows + R
 Type:
odbcad32
and press Enter.

3. Create a New Data Source Name (DSN)


 Select System DSN tab.
 Click Add button.
 Choose the appropriate ODBC driver (e.g., Microsoft Access Driver).
 Click Finish.

4. Configure the Data Source


 Enter the Data Source Name.
Example:
Data Source Name : StudentDSN
 Click Select.
 Browse and select the database file.
 Click OK.
5. Save the DSN
 Verify the configuration.
 Save the DSN settings.
 The DSN now acts as a bridge between the database and Java application.

6. Load JDBC–ODBC Bridge Driver


In the Java program, load the driver.
[Link]("[Link]");

7. Establish Connection Using DSN


Create a connection using the DSN name.
Connection con =
[Link](
"jdbc:odbc:StudentDSN");

8. Create Statement Object


Statement st =
[Link]();

9. Execute SQL Query


ResultSet rs =
[Link](
"SELECT * FROM Student");

10. Process the Result


while([Link]())
{
[Link](
[Link](1)+" "+
[Link](2));
}

11. Close the Connection


[Link]();
[Link]();
[Link]();

Neat Diagram
Java Application


JDBC API


JDBC–ODBC Bridge


ODBC Driver


Database

Advantages
1. Easy to implement.
2. Supports existing ODBC drivers.
3. Useful for small applications.
Disadvantages
1. Requires ODBC installation.
2. Platform dependent.
3. Low performance.
4. Removed from newer Java versions.

[Link] the four types of jdbc drivers


Four Types of JDBC Drivers (10 Marks)
Introduction
A JDBC Driver is a software component that enables a Java application to
communicate with a database. JDBC provides four types of drivers for
database connectivity.

1. Type-1 Driver (JDBC–ODBC Bridge Driver)


Definition
Converts JDBC calls into ODBC calls and then communicates with the
database through the ODBC driver.
Architecture
Java Application

JDBC API

JDBC-ODBC Bridge

ODBC Driver

Database
Advantages
 Easy to use.
 Suitable for small applications.
Disadvantages
 Low performance.
 Requires ODBC installation.
 Platform dependent.

2. Type-2 Driver (Native API Driver)


Definition
Converts JDBC calls into database-specific native API calls.
Architecture
Java Application

JDBC API

Native API Driver

Database Native Library

Database
Advantages
 Better performance than Type-1.
 Uses database-specific features.
Disadvantages
 Requires native libraries.
 Platform dependent.

3. Type-3 Driver (Network Protocol Driver)


Definition
Converts JDBC calls into a database-independent network protocol and
sends them to a middleware server.
Architecture
Java Application

JDBC API

Network Protocol Driver

Middleware Server

Database
Advantages
 Platform independent.
 Can connect to multiple databases.
 No native libraries required.
Disadvantages
 Requires middleware server.
 Additional network overhead.

4. Type-4 Driver (Thin Driver)


Definition
Directly converts JDBC calls into the database-specific protocol and
communicates with the database.
Architecture
Java Application

JDBC API

Type-4 Driver

Database
Advantages
 High performance.
 Platform independent.
 No middleware or native libraries required.
 Most widely used.
Disadvantages
 Database-specific driver needed.

Comparison Table

Platform Performan
Type Driver Name
Independent ce

Type- JDBC–ODBC
No Low
1 Bridge

Type-
Native API No Medium
2

Type- Network
Yes Good
3 Protocol

Type-
Thin Driver Yes Excellent
4

[Link] are database drivers


Database Drivers (4 Marks)
Definition
A Database Driver (JDBC Driver) is a software component that enables
a Java application to communicate with a database. It converts JDBC calls
into database-specific commands and sends them to the database.
Functions of JDBC Driver
 Establishes connection between Java application and database.
 Translates JDBC commands into database-specific commands.
 Executes SQL queries and updates.
 Returns results from the database to the Java program.
Types of JDBC Drivers
1. Type-1 Driver – JDBC-ODBC Bridge Driver
2. Type-2 Driver – Native API Driver
3. Type-3 Driver – Network Protocol Driver
4. Type-4 Driver – Thin Driver
12. Describe the various steps of jdbc with code snippet for 12
marks
Various Steps of JDBC with Code Snippet (12 Marks)
Introduction
JDBC (Java Database Connectivity) is an API used to connect Java
applications with databases. It provides methods to execute SQL queries
and retrieve results from the database.

Steps Involved in JDBC


1. Import JDBC Packages
Import the required JDBC classes.
import [Link].*;

2. Load and Register the Driver


Load the JDBC driver into memory.
[Link]("[Link]");

3. Establish Connection
Create a connection with the database.
Connection con = [Link](
"jdbc:mysql://localhost:3306/studentdb",
"root",
"password");

4. Create Statement Object


Create a Statement object to send SQL commands.
Statement st = [Link]();

5. Execute SQL Query


Execute the SQL statement.
ResultSet rs =
[Link]("SELECT * FROM Student");
For INSERT/UPDATE/DELETE:
[Link]("INSERT INTO Student VALUES(101,'Ali')");

6. Process the ResultSet


Retrieve data from the ResultSet object.
while([Link]())
{
[Link](
[Link](1)+" "+
[Link](2));
}

7. Close the Resources


Close all JDBC objects.
[Link]();
[Link]();
[Link]();

Complete JDBC Program


import [Link].*;

class JdbcDemo
{
public static void main(String args[])
{
try
{
// Load Driver
[Link]("[Link]");

// Establish Connection
Connection con =
[Link](
"jdbc:mysql://localhost:3306/studentdb",
"root",
"password");

// Create Statement
Statement st =
[Link]();

// Execute Query
ResultSet rs =
[Link](
"SELECT * FROM Student");

// Process Result
while([Link]())
{
[Link](
[Link](1)+" "+
[Link](2));
}

// Close Resources
[Link]();
[Link]();
[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}

JDBC Architecture Diagram


Java Application

JDBC API

JDBC Driver

Database

Advantages of JDBC
 Platform independent.
 Supports multiple databases.
 Easy execution of SQL queries.
 Provides secure database access.
 Supports transaction processing.
13. Describe the following concept one scrollbal result set 2
calibrible statement 3 transaction processing for updatetable
result set for 12 marks answer
Describe the Following Concepts in JDBC (12 Marks)
1. Scrollable ResultSet
Definition
A Scrollable ResultSet allows the cursor to move both forward and
backward through the records of a ResultSet. Unlike a normal
ResultSet, it is not restricted to moving only in the forward
direction.
Creating Scrollable ResultSet
Statement st = [Link](
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Common Methods
 next() – Move to next row
 previous() – Move to previous row
 first() – Move to first row
 last() – Move to last row
 absolute(n) – Move to nth row
Advantages
 Easy navigation of records.
 Supports forward and backward movement.
 Improves flexibility in data retrieval.

2. CallableStatement
Definition
A CallableStatement is used to call stored procedures and
functions stored in the database.
Syntax
CallableStatement cs =
[Link]("{call procedure_name(?,?)}");
Example
CallableStatement cs =
[Link]("{call addStudent(?,?)}");

[Link](1,101);
[Link](2,"Ali");

[Link]();
Advantages
 Executes stored procedures efficiently.
 Supports IN, OUT, and INOUT parameters.
 Reduces network traffic.

3. Transaction Processing
Definition
A Transaction is a group of SQL statements executed as a single
unit. Either all statements are executed successfully or none of
them are executed.
Important Methods
[Link](false);
[Link]();
[Link]();
Example
[Link](false);

[Link](
"UPDATE Account SET Balance=Balance-1000 WHERE
AccNo=101");

[Link](
"UPDATE Account SET Balance=Balance+1000 WHERE
AccNo=102");

[Link]();
If an error occurs:
[Link]();
Advantages
 Maintains data consistency.
 Ensures data integrity.
 Supports error recovery.

4. Updatable ResultSet
Definition
An Updatable ResultSet allows modification of database records
directly through the ResultSet object without writing separate
UPDATE statements.
Creating Updatable ResultSet
Statement st = [Link](
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
Example
ResultSet rs =
[Link]("SELECT * FROM Student");

[Link]();
[Link]("Name","Ahmed");
[Link]();
Advantages
 Direct modification of records.
 Simplifies database updates.
 Reduces coding effort.

14. Explain different kinds of exceptions in database


Different Kinds of Exceptions in JDBC (6 Marks)
Definition
An Exception is an error that occurs during the execution of a
JDBC program. JDBC provides exception classes to identify and
handle database-related errors.
1. SQLException
Definition
SQLException is the most common JDBC exception. It occurs when
there is an error while connecting to the database or executing
SQL statements.
Example
Connection con =
[Link]("wrong_url");
Causes
 Invalid database URL.
 Incorrect SQL query.
 Database connection failure.
 Table or column does not exist.

2. SQLWarning
Definition
SQLWarning represents a database warning. It does not stop
program execution but informs the user about minor issues.
Example
SQLWarning warning = [Link]();
Causes
 Data truncation.
 Use of deprecated database features.
 Minor database-related warnings.

3. BatchUpdateException
Definition
BatchUpdateException occurs when an error happens during the
execution of a batch of SQL statements.
Example
Statement st = [Link]();

[Link]("INSERT INTO Student VALUES(1,'Ali')");


[Link]("Wrong SQL Statement");

[Link]();
Causes
 Invalid SQL statement in batch.
 Constraint violation.
 Database update failure.

15. Write a note on one transaction processing in jdbc 2 types of


exception occurred in jdbc
1. Transaction Processing in JDBC
Definition
A Transaction is a group of SQL statements executed as a single
unit of work. Either all statements are executed successfully
(Commit) or none are executed (Rollback).
Need for Transaction Processing
 Maintains data consistency.
 Prevents partial updates.
 Ensures data integrity.
 Supports recovery from failures.
Important Methods
[Link](false);
[Link]();
[Link]();
Example
Connection con = [Link](url,user,pwd);

[Link](false);

Statement st = [Link]();

[Link](
"UPDATE Account SET Balance=Balance-1000 WHERE
AccNo=101");

[Link](
"UPDATE Account SET Balance=Balance+1000 WHERE
AccNo=102");

[Link]();
If an error occurs:
[Link]();
Advantages
 Ensures consistency of data.
 Prevents data loss.
 Supports error recovery.
 Improves reliability.

2. Types of Exceptions Occurred in JDBC


Definition
Exceptions are errors that occur during the execution of JDBC
programs. JDBC provides exception classes to handle database-
related errors.
a) SQLException
Definition:
Occurs when there is an error in database access or SQL
execution.
Example:
Connection con =
[Link]("wrong_url");
Causes:
 Invalid database URL.
 Incorrect SQL query.
 Connection failure.

b) SQLWarning
Definition:
Represents a database warning that does not stop program
execution.
Example:
SQLWarning warning =
[Link]();
Causes:
 Data truncation.
 Deprecated database features.
 Minor database warnings.

c) BatchUpdateException
Definition:
Occurs when an error happens during batch processing of SQL
statements.
Example:
Statement st = [Link]();

[Link]("INSERT INTO Student VALUES(1,'Ali')");


[Link]("Wrong SQL Statement");

[Link]();
Causes:
 Invalid SQL statement in batch.
 Constraint violation.
 Update failure.

16. Write a java program to insert data into student database and
retrieve information based on particular queries explain update
delete search

ava Program to Insert, Retrieve, Update, Delete and Search


Student Records Using JDBC (12 Marks)
Student Table
Student(RollNo, Name, Marks)

Java Program
import [Link].*;

public class StudentDB


{
public static void main(String args[])
{
try
{
// Load Driver
[Link]("[Link]");

// Establish Connection
Connection con =
[Link](
"jdbc:mysql://localhost:3306/studentdb",
"root",
"password");

Statement st = [Link]();

// INSERT
[Link](
"INSERT INTO Student VALUES(101,'Ali',85)");

// RETRIEVE (DISPLAY)
ResultSet rs =
[Link]("SELECT * FROM Student");

[Link]("Student Records");
while([Link]())
{
[Link](
[Link]("RollNo")+" "+
[Link]("Name")+" "+
[Link]("Marks"));
}

// UPDATE
[Link](
"UPDATE Student SET Marks=90 WHERE RollNo=101");

// SEARCH
rs = [Link](
"SELECT * FROM Student WHERE RollNo=101");

while([Link]())
{
[Link](
"Found : "+
[Link]("Name"));
}

// DELETE
[Link](
"DELETE FROM Student WHERE RollNo=101");

[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}

Explanation of Operations
1. Insert Operation
Used to add a new student record.
[Link](
"INSERT INTO Student VALUES(101,'Ali',85)");
Purpose: Inserts a new row into the Student table.

2. Retrieve Operation
Used to display all records.
ResultSet rs =
[Link]("SELECT * FROM Student");
Purpose: Fetches all student records from the database.

3. Update Operation
Used to modify existing records.
[Link](
"UPDATE Student SET Marks=90 WHERE RollNo=101");
Purpose: Updates the marks of the student.

4. Search Operation
Used to find a specific record.
rs = [Link](
"SELECT * FROM Student WHERE RollNo=101");
Purpose: Searches for a student based on Roll Number.

5. Delete Operation
Used to remove records.
[Link](
"DELETE FROM Student WHERE RollNo=101");
Purpose: Deletes the specified student record.

JDBC Process Flow


Java Program

JDBC Driver

Database Connection

Execute SQL Queries

Display Results

17. Write a notes on one result set to transaction processing


1. ResultSet
Definition
A ResultSet is an object in JDBC that stores the data returned by a SQL
SELECT query. It allows the programmer to retrieve and process records from the
database.
Creating ResultSet
Statement st = [Link]();
ResultSet rs =
[Link]("SELECT * FROM Student");
Common Methods

Method Purpose

next() Moves to next record

previous Moves to previous


() record

first() Moves to first row

last() Moves to last row

Retrieves integer
getInt()
value

getStrin
Retrieves string value
g()

Example
while([Link]())
{
[Link](
[Link](1)+" "+
[Link](2));
}
Advantages
 Stores query results.
 Easy retrieval of records.
 Supports navigation through rows.
 Provides access to column values.

2. Transaction Processing
Definition
A Transaction is a group of SQL statements executed as a single unit of
work. Either all operations are completed successfully (Commit) or all are
cancelled (Rollback).
Need for Transaction Processing
 Maintains data consistency.
 Prevents partial updates.
 Ensures data integrity.
 Supports error recovery.
Important Methods
[Link](false);
[Link]();
[Link]();
Example
[Link](false);

Statement st = [Link]();

[Link](
"UPDATE Account SET Balance=Balance-1000 WHERE AccNo=101");

[Link](
"UPDATE Account SET Balance=Balance+1000 WHERE AccNo=102");

[Link]();
If any error occurs:
[Link]();
Advantages
 Maintains database consistency.
 Ensures reliable execution.
 Prevents data loss.
 Supports recovery from failures.

Difference Between ResultSet and Transaction Processing

ResultSet Transaction Processing

Manages multiple SQL


Stores query results
operations

Used with INSERT, UPDATE,


Used with SELECT queries
DELETE

Retrieves data Maintains data consistency

Uses next(), getInt(),


Uses commit() and rollback()
getString()

18. Write a program to execute a database transaction


Program to Execute a Database Transaction in JDBC (12 Marks)
Aim
To perform a database transaction using JDBC. If all SQL statements
execute successfully, the transaction is committed; otherwise, it is rolled back.

Program
import [Link].*;

public class TransactionDemo


{
public static void main(String args[])
{
try
{
// Load Driver
[Link]("[Link]");

// Establish Connection
Connection con =
[Link](
"jdbc:mysql://localhost:3306/bankdb",
"root",
"password");
// Disable Auto Commit
[Link](false);

Statement st =
[Link]();

// Debit Amount
[Link](
"UPDATE Account SET Balance=Balance-1000 WHERE AccNo=101");

// Credit Amount
[Link](
"UPDATE Account SET Balance=Balance+1000 WHERE AccNo=102");

// Commit Transaction
[Link]();

[Link](
"Transaction Completed Successfully");

[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}

Transaction with Rollback


try
{
[Link](false);

[Link](sql1);
[Link](sql2);

[Link]();
}
catch(Exception e)
{
[Link]();

[Link](
"Transaction Rolled Back");
}
Explanation
1. Load JDBC Driver
[Link]("[Link]");
Loads the JDBC driver.
2. Establish Connection
Connection con =
[Link](url,user,password);
Connects Java application to the database.
3. Disable Auto Commit
[Link](false);
Allows multiple SQL statements to be treated as one transaction.
4. Execute SQL Statements
[Link](sql);
Performs database operations.
5. Commit Transaction
[Link]();
Permanently saves all changes.
6. Rollback Transaction
[Link]();
Cancels all changes if an error occurs.

Flow Diagram
Start

Load Driver

Establish Connection

setAutoCommit(false)

Execute SQL Statements

Success?
┌───────┴───────┐
Yes No
↓ ↓
Commit Rollback
↓ ↓
Close Connection

Stop

Advantages of Transaction Processing


 Maintains data consistency.
 Prevents partial updates.
 Ensures data integrity.
 Supports error recovery.
 Improves database reliability.

[Link] jdbc multi tyre architecture with me diagram that is driver


types in detail
JDBC Multi-Tier Architecture and Driver Types (12 Marks)
Introduction
JDBC (Java Database Connectivity) is an API used to connect Java
applications with databases. In a multi-tier architecture, JDBC acts as a bridge
between the Java application and the database using JDBC drivers.

JDBC Multi-Tier Architecture


Neat Diagram
Client (Browser/User)


Presentation Layer
(JSP/Servlet)


Business Logic Layer
(Java Code)


JDBC API


JDBC Driver


Database
Explanation
1. Client sends a request.
2. JSP/Servlet receives the request.
3. Business layer processes the request.
4. JDBC API communicates with the JDBC driver.
5. JDBC driver interacts with the database.
6. Results are returned to the client.
Advantages
 Better security.
 Easy maintenance.
 Improved scalability.
 Efficient database access.

Types of JDBC Drivers


1. Type-1 Driver (JDBC-ODBC Bridge Driver)
Diagram
Java Application

JDBC API

JDBC-ODBC Bridge

ODBC Driver

Database
Advantages
 Easy to use.
 Suitable for small applications.
Disadvantages
 Slow performance.
 Requires ODBC installation.
 Platform dependent.

2. Type-2 Driver (Native API Driver)


Diagram
Java Application

JDBC API

Native API Driver

Native Library

Database
Advantages
 Faster than Type-1.
 Uses database-specific features.
Disadvantages
 Platform dependent.
 Requires native libraries.

3. Type-3 Driver (Network Protocol Driver)


Diagram
Java Application

JDBC API

Network Protocol Driver

Middleware Server

Database
Advantages
 Platform independent.
 Supports multiple databases.
 No native libraries required.
Disadvantages
 Requires middleware server.
 Extra network overhead.

4. Type-4 Driver (Thin Driver)


Diagram
Java Application

JDBC API

Type-4 Driver

Database
Advantages
 High performance.
 Platform independent.
 No middleware required.
 Most widely used.
Disadvantages
 Database-specific driver required.

Comparison of JDBC Drivers

Platform Performan
Driver Type
Independent ce

Type-1 (JDBC-ODBC) No Low

Type-2 (Native API) No Medium

Type-3 (Network
Yes Good
Protocol)

Type-4 (Thin Driver) Yes Excellent

[Link] a note on database metadata object methods and result set Meta
data object methods for 12 mark
DatabaseMetaData Object Methods and ResultSetMetaData
Object Methods (12 Marks)
Introduction
Metadata means "data about data." In JDBC, metadata provides
information about the database, tables, columns, driver, and query
results.
There are two important metadata interfaces:
1. DatabaseMetaData
2. ResultSetMetaData
1. DatabaseMetaData Object
Definition
DatabaseMetaData is an interface that provides information about
the database, JDBC driver, tables, and database capabilities.
Creating DatabaseMetaData Object
Connection con = [Link](url,user,pwd);

DatabaseMetaData dbmd =
[Link]();
Important Methods

Method Description

getDatabaseProductNa
Returns database name
me()

getDatabaseProductVer
Returns database version
sion()

getDriverName() Returns JDBC driver name

getDriverVersion() Returns driver version

getUserName() Returns current username

getURL() Returns database URL

getTables() Returns information about tables

supportsTransactions() Checks transaction support

supportsBatchUpdates(
Checks batch update support
)

Returns maximum connections


getMaxConnections()
supported

Example
DatabaseMetaData dbmd =
[Link]();

[Link](
[Link]());

[Link](
[Link]());
Uses
 Retrieves database information.
 Retrieves driver details.
 Checks database features and capabilities.

2. ResultSetMetaData Object
Definition
ResultSetMetaData is an interface that provides information
about the columns of a ResultSet.
Creating ResultSetMetaData Object
Statement st =
[Link]();

ResultSet rs =
[Link](
"SELECT * FROM Student");

ResultSetMetaData rsmd =
[Link]();
Important Methods

Method Description

getColumnCount() Returns number of columns

getColumnName(int) Returns column name

getColumnType(int) Returns column type

getColumnTypeName
Returns SQL type name
(int)

getTableName(int) Returns table name

getColumnDisplaySiz
Returns column width
e(int)

Checks whether column allows


isNullable(int)
NULL values

Example
ResultSetMetaData rsmd =
[Link]();

[Link](
"Columns = "
+ [Link]());

[Link](
[Link](1));
Uses
 Retrieves column information.
 Determines column data types.
 Generates dynamic reports.
 Helps in displaying query results.

Difference Between DatabaseMetaData and ResultSetMetaData

DatabaseMetaData ResultSetMetaData

Provides information Provides information about query


about database result columns

Obtained from Connection


Obtained from ResultSet object
object

Gives driver and database


Gives column details
details

Used for database


Used for result analysis
analysis

You might also like