Advanced Java Programming · Unit 4 · 4 hrs
Database Connectivity
Exam-focused notes for Database Connectivity (Advanced Java Programming, CSC419): what the TU syllabus asks and how it has actually been tested, with 9 solved past questions from this unit.
Database Connectivity in short
This unit covers how a Java program talks to a relational database through JDBC: the architecture and driver types behind a connection, the objects used to run SQL and read back results, and the transaction and safety practices that make database code correct.
What this unit covers
- JDBC Architecture, JDBC Driver Types, JDBC Configuration, Managing Connections, Statements, Result Set, SQL Exceptions
- DDL and DML Operations using Java, Prepared Statements, Multiple Results, Scrollable Result Sets, Updateable Result Sets, Row Sets and Cached Row Sets, Transactions, SQL Escapes
DDL and DML Operations using Java, Prepared Statements, Multiple Results, Scrollable Result Sets, Updateable Result Sets, Row Sets and Cached Row Sets, Transactions, SQL Escapes
2081 · 5 marks
What do you mean by SQL escape? Describe about scrollable and updateable result sets. [5]
Show solved answerHide answer
SQL Escape and Scrollable/Updateable Result Sets
1. SQL Escape
SQL Escape (also called SQL escape syntax) is a standard JDBC mechanism that allows Java programs to use database-independent SQL syntax for features that differ across database vendors (such as date literals, stored procedure calls, outer joins, scalar functions, etc.).
JDBC translates the escape syntax into the database-specific SQL before sending the query, making the code portable across different databases.
Common SQL Escape Syntax:
| Purpose | Escape Syntax Example |
|---|---|
| Date literal | {d 'yyyy-mm-dd'} |
| Time literal | {t 'hh:mm:ss'} |
| Timestamp | {ts 'yyyy-mm-dd hh:mm:ss'} |
| Stored procedure call | {call procedureName(params)} |
| Scalar function | {fn functionName(args)} |
| Outer join | {oj table1 LEFT OUTER JOIN table2 ON ...} |
Example:
String sql = "SELECT * FROM orders WHERE order_date = {d '2024-01-15'}";
PreparedStatement ps = con.prepareStatement(sql);
Here {d '2024-01-15'} is the escape sequence that JDBC translates to the vendor-specific date format automatically.
2. Scrollable Result Sets
By default, a ResultSet in JDBC is forward-only (can only move forward using next()). A Scrollable Result Set allows the cursor to move in both directions and jump to any row.
Types of Scrollable Result Sets:
| Type | Constant | Description |
|---|---|---|
| Forward Only | TYPE_FORWARD_ONLY | Default; cursor moves forward only |
| Scroll Insensitive | TYPE_SCROLL_INSENSITIVE | Scrollable; does NOT reflect changes made to DB |
| Scroll Sensitive | TYPE_SCROLL_SENSITIVE | Scrollable; reflects changes made to DB |
Navigation Methods:
rs.next(); // Move to next row
rs.previous(); // Move to previous row
rs.first(); // Move to first row
rs.last(); // Move to last row
rs.absolute(n); // Move to nth row
rs.relative(n); // Move n rows from current position
Creating a Scrollable Result Set:
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY
);
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
3. Updateable Result Sets
An Updateable Result Set allows the program to insert, update, or delete rows directly through the ResultSet object without writing separate SQL UPDATE/DELETE statements.
Concurrency Modes:
| Mode | Constant | Description |
|---|---|---|
| Read Only | CONCUR_READ_ONLY | Default; cannot update through ResultSet |
| Updatable | CONCUR_UPDATABLE | Allows updates through ResultSet |
Common Update Methods:
rs.updateString("name", "New Name"); // Update a column value
rs.updateRow(); // Commit the update to DB
rs.deleteRow(); // Delete current row
rs.moveToInsertRow(); // Move to insert buffer
rs.insertRow(); // Insert the new row
4. Scrollable AND Updateable Result Set (Combined)
As stated in the notes, to create a scrollable insensitive result set which is also updatable, the statement must be created with both scroll type and updatable concurrency mode:
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, // Scrollable
ResultSet.CONCUR_UPDATABLE // Updatable
);
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
// Scroll to row 3 and update
rs.absolute(3);
rs.updateString("name", "Ram Sharma");
rs.updateRow(); // Changes saved to database
Summary Table:
| Feature | Default RS | Scrollable RS | Updateable RS | Scrollable + Updateable |
|---|---|---|---|---|
| Forward only | Yes | No | Yes | No |
| Bidirectional | No | Yes | No | Yes |
| Update rows | No | No | Yes | Yes |
Key Point: A scrollable updatable result set maintains a cursor that can both scroll (move in any direction) and update rows directly in the underlying database table.
2080 · 5 marks
Assume a table MOVIE(id, title, genre). Now, using JDBC, perform the following queries; a. Add any three records to the MOVIE table. b. Using a prepared statement, update the genre to 'Comedy' having the title 'Jatra'. [5]
2078 · 5 marks
What is row set? Explain cached row set in detail. [5]
2077 · 10 marks
You are hired by a reputed software company which is going to design an application for 'Movie Rental System'. Your responsibility is to design a schema named MRS and create a table named Movie(id, Title, Genre, Language, Length). Write a program to design a GUI form to take input for this table and insert the data into table after clicking the OK button.[10]
2076 · 5 marks
What are the benefits of using JDBC? What is prepared statement? [5]
2075 · 5 marks
How prepared statements are different with statement? List the types of JDBC driver. [5]
Show solved answerHide answer
Prepared Statements vs Statement & JDBC Driver Types
Part 1: Difference Between PreparedStatement and Statement
| Feature | Statement | PreparedStatement |
|---|---|---|
| Definition | Used to execute simple, static SQL queries | Used to execute precompiled, parameterized SQL queries |
| SQL Compilation | SQL is compiled every time it is executed | SQL is compiled only once and reused |
| Parameters | Does not support parameters; query is hardcoded | Supports ? placeholders for dynamic parameters |
| Performance | Slower for repeated execution | Faster for repeated execution due to precompilation |
| SQL Injection | More vulnerable to SQL injection attacks | More secure; prevents SQL injection |
| Usage | Suitable for queries executed once | Suitable for queries executed multiple times with different values |
Example of Statement:
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE id = 1");
Example of PreparedStatement:
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 1);
ResultSet rs = pstmt.executeQuery();
Part 2: Types of JDBC Drivers
There are 4 types of JDBC drivers:
Type 1: JDBC-ODBC Bridge Driver
- Converts JDBC method calls into ODBC method calls.
- Requires an ODBC driver to be installed and configured on the client machine.
- Does not directly interact with the database.
- Can connect to any type of database.
- Least efficient due to multiple layers of conversion.
Type 2: Native-API Driver
- Written partially in Java and partially in native code.
- Converts JDBC method calls into native calls of the database API.
- The Native-API of the specific database must be installed on the client system before use.
- Faster than Type 1 but still requires native installation.
Type 3: Net Pure Java Driver (Network Protocol Driver)
- Fully written in Java.
- The JDBC driver on the client machine uses a socket to communicate with middleware at the server.
- Client database access requests are sent through the network to the middleware, which then communicates with the database.
- No client-side database installation required.
Type 4: Pure Java Driver (Thin Driver)
- Fully written in Java, hence it is a portable driver.
- Interacts directly with the database without any middleware or native library.
- No client-side or server-side installation required.
- Most commonly used driver in modern applications.
Summary: Type 4 (Pure Java Driver) is the most preferred driver due to its portability, direct database interaction, and no dependency on native libraries.
JDBC Architecture, JDBC Driver Types, JDBC Configuration, Managing Connections, Statements, Result Set, SQL Exceptions
2080 · 5 marks
Describe the role of Result Sets. What is wrong in the following code?
public class Point {
int p;
public void setP(int p) {
p = p;
}
}
[5]
2079 · 5 marks
Explain JDBC driver types. What is scrollable result set? [5]
2078 · 5 marks
Write short notes on: a. JDBC drivers b. Java server pages [2.5+2.5]
Make Unit 4 stick
Practice CSC419 with flashcards & quizzes