Java 5
Java 5
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.
[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.
PreparedStatement CallableStatement
Example Program
Connection con = [Link](url,user,pwd);
[Link](false);
Statement st = [Link]();
[Link]();
If any error occurs:
[Link]();
Advantages
Ensures data integrity.
Maintains database consistency.
Prevents data loss.
Supports error recovery.
Improves reliability of database operations.
Platform Performan
Type Driver Name
Independent ce
Type-
JDBC-ODBC Bridge No Low
1
Type-
Native API Driver No Medium
2
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.
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];
[Link]("[Link]");
[Link]("jdbc:mysql://localhost:3306/studentdb");
[Link]("root");
[Link]("root");
[Link]("Connection Obtained");
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.
3. Establish Connection
Create a connection between Java application and database.
Connection con = [Link](
"jdbc:mysql://localhost:3306/studentdb",
"root",
"password");
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);
}
}
}
Method Description
getDatabaseProductNam
Returns the database name.
e()
getDatabaseProductVersi
Returns the database version.
on()
Example
Connection con = [Link](url,user,pwd);
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.
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.
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
3. Establish Connection
Create a connection with the database.
Connection con = [Link](
"jdbc:mysql://localhost:3306/studentdb",
"root",
"password");
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);
}
}
}
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.
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]();
Causes
Invalid SQL statement in batch.
Constraint violation.
Database update failure.
[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.
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]();
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
Java Program
import [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.
Method Purpose
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.
Program
import [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);
}
}
}
[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
Platform Performan
Driver Type
Independent ce
Type-3 (Network
Yes Good
Protocol)
[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()
supportsBatchUpdates(
Checks batch update support
)
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
getColumnTypeName
Returns SQL type name
(int)
getColumnDisplaySiz
Returns column width
e(int)
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.
DatabaseMetaData ResultSetMetaData