4 Database Connectivity

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.

Database Connectivity: notes

JDBC Architecture, JDBC Driver Types, JDBC Configuration, Managing Connections, Statements, Result Set, SQL Exceptions

JDBC (Java Database Connectivity) is the standard Java API for database-independent connectivity between a Java program and a relational database. It covers making a connection, building and sending SQL statements, executing queries, and reading back or modifying the resulting records.

The JDBC architecture has two layers. The JDBC API provides the application-to-driver-manager connection that the programmer's code talks to directly. The JDBC Driver API supports the driver-manager-to-driver connection underneath it, where the actual translation to a specific database's wire protocol happens. The API exposes a small set of core types: DriverManager manages the list of registered database drivers and matches a connection request to the right one; Driver is the interface each database vendor implements to handle the low-level communication with its server; Connection represents an open session with the database, and all communication happens through it; Statement (and its subinterfaces) is used to submit SQL to the database; ResultSet holds the rows returned by a query; and SQLException reports errors from the database or the driver.

There are four JDBC driver types:

TypeNameHow it works
Type 1JDBC-ODBC BridgeTranslates JDBC calls into ODBC calls, so it needs an ODBC driver installed and configured on the client; can reach almost any database but adds an extra translation layer.
Type 2Native-API driverPartly Java, partly native code; converts JDBC calls into the database's own native client API calls, so that vendor's native library must be installed on the client.
Type 3Network Protocol (Net Pure Java) driverPure Java on the client, but talks to middleware server software over a network protocol, which then relays the request to the actual database; no native code is needed on the client.
Type 4Thin (Pure Java) driverWritten entirely in Java and talks directly to the database over its own network protocol; needs no client-side or server-side installation beyond the driver itself, which is why it is the most commonly used type today.

JDBC configuration to reach a database (for example MySQL) needs four pieces of information: the driver class (for MySQL, com.mysql.cj.jdbc.Driver), the connection URL (of the form jdbc:mysql://host:port/databaseName, for example jdbc:mysql://localhost:3306/college), a username, and a password.

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 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:

PurposeEscape 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:

TypeConstantDescription
Forward OnlyTYPE_FORWARD_ONLYDefault; cursor moves forward only
Scroll InsensitiveTYPE_SCROLL_INSENSITIVEScrollable; does NOT reflect changes made to DB
Scroll SensitiveTYPE_SCROLL_SENSITIVEScrollable; reflects changes made to DB
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:

ModeConstantDescription
Read OnlyCONCUR_READ_ONLYDefault; cannot update through ResultSet
UpdatableCONCUR_UPDATABLEAllows 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:

FeatureDefault RSScrollable RSUpdateable RSScrollable + Updateable
Forward onlyYesNoYesNo
BidirectionalNoYesNoYes
Update rowsNoNoYesYes

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.

Open this answer on its own page →

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]

--- --- Step Method Used Purpose ---------------------------- Load driver Class.forName() Registers MySQL JDBC driver Connect DriverManager.getConnection() Opens DB connection Insert records stmt.executeUpdate() Returns number of rows affected Prepared statement con.prepareStatement(sql) Pre-comp...

Open this answer on its own page →

2078 · 5 marks

What is row set? Explain cached row set in detail. [5]

A RowSet is a Java interface that extends the ResultSet interface and provides a more flexible and convenient way to handle tabular data from a database. It is part of the javax.sql package. - It is a JavaBean component, meaning it supports event handling, serialization, and can be used in GUI en...

Open this answer on its own page →

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]

--- Note: Java AWT (Abstract Windowing Toolkit) is used to develop GUI/window-based applications. JDBC interfaces such as Connection, Statement, and ResultSet are used to communicate with the database. A Type 4 (Pure Java) JDBC driver is used here as it directly interacts with the database and is...

Open this answer on its own page →

2076 · 5 marks

What are the benefits of using JDBC? What is prepared statement? [5]

--- JDBC (Java Database Connectivity) is a Java API that enables Java applications to interact with databases. The key benefits are: 1. Platform Independence / Cross-Platform: JDBC is cross-platform, meaning Java applications using JDBC can run on any operating system without modification. 2. Dat...

Open this answer on its own page →

2075 · 5 marks

How prepared statements are different with statement? List the types of JDBC driver. [5]

Show solved answer

Prepared Statements vs Statement & JDBC Driver Types


Part 1: Difference Between PreparedStatement and Statement

FeatureStatementPreparedStatement
DefinitionUsed to execute simple, static SQL queriesUsed to execute precompiled, parameterized SQL queries
SQL CompilationSQL is compiled every time it is executedSQL is compiled only once and reused
ParametersDoes not support parameters; query is hardcodedSupports ? placeholders for dynamic parameters
PerformanceSlower for repeated executionFaster for repeated execution due to precompilation
SQL InjectionMore vulnerable to SQL injection attacksMore secure; prevents SQL injection
UsageSuitable for queries executed onceSuitable 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.

Open this answer on its own page →

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]

--- A Result Set in Java (specifically java.sql.ResultSet) represents the result of a database query. It acts as a cursor that points to the data returned from executing a SQL SELECT statement via JDBC. Role Description ------------------- Data Retrieval Holds the rows returned by a SQL query fro...

Open this answer on its own page →

2079 · 5 marks

Explain JDBC driver types. What is scrollable result set? [5]

There are 4 types of JDBC drivers: --- - To use a Type 1 driver, an ODBC driver must be installed and configured on the client machine. - This driver does not directly interact with the database. - It converts JDBC method calls into ODBC method calls, which then communicate with the database. - I...

Open this answer on its own page →

2078 · 5 marks

Write short notes on: a. JDBC drivers b. Java server pages [2.5+2.5]

--- JDBC (Java Database Connectivity) provides a standard API for Java applications to interact with databases. A JDBC driver is a software component that enables Java applications to communicate with a database by translating JDBC method calls into database-specific calls. Type 1: JDBC-ODBC Brid...

Open this answer on its own page →