5 Database Connectivity With Jdbc

Advanced Java Programming · Unit 5

Database Connectivity with JDBC

Exam-focused notes for Database Connectivity with JDBC (Advanced Java Programming, BIT401): what the TU syllabus asks and how it has actually been tested, with 6 solved past questions from this unit.

Database Connectivity with JDBC in short

JDBC (Java Database Connectivity) is the Java API for talking to relational databases. It lets one program work with many databases by changing only the driver.

Database Connectivity with JDBC: notes

JDBC architecture and driver types

The architecture has two layers. The JDBC API (java.sql) is what the programmer uses. The JDBC Driver Manager loads drivers and picks the right one. A driver talks to a specific database. The main interfaces are Driver, Connection, Statement, PreparedStatement, ResultSet.

Java application -> JDBC API -> Driver Manager -> JDBC driver -> Database

There are four driver types.

TypeNameHow it works
1JDBC-ODBC bridgeConverts JDBC calls to ODBC calls. Needs an ODBC driver. Removed from Java 8
2Native-APIConverts calls to the database's native client library. Needs client software
3Network protocolSends calls to a middle server, which talks to the database. Pure Java client
4Thin driverPure Java. Speaks the database protocol directly. Most common today

Type 4 is the fastest and easiest to deploy. It needs no native code on the client.

Type 0 JDBC driver

There is no standard "Type 0" JDBC driver. The official classification has only Types 1 to 4. If a question uses the name, say so clearly, then describe the driver that comes closest to a direct connection. That is the Type 4 thin driver. It is pure Java, needs no client software, and talks to the database in the database's own protocol. Modern programs use it.

Steps of JDBC connection

  • Load the driver (automatic in JDBC 4 and later when the jar is on the classpath).
  • Open a connection with DriverManager.getConnection(url, user, password).
  • Create a Statement or PreparedStatement.
  • Run the query with executeQuery() or executeUpdate().
  • Process the ResultSet.
  • Close the resources.
import java.sql.*;

public class JdbcDemo {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/school";
        try (Connection con = DriverManager.getConnection(url, "root", "pass");
             Statement st = con.createStatement();
             ResultSet rs = st.executeQuery("SELECT id, name FROM student")) {
            while (rs.next()) {
                System.out.println(rs.getInt("id") + " " + rs.getString("name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

executeQuery() returns a ResultSet for SELECT. executeUpdate() returns the number of rows changed for INSERT, UPDATE and DELETE.

What this unit covers

  • JDBC architecture and driver types
  • Steps of JDBC connection
  • Statement and PreparedStatement
  • Differences between Statement and PreparedStatement
  • Handling multiple result sets
  • Database connection from JSP
  • Type 0 JDBC driver

Database connection from JSP

2082 · 5 marks

How do you connect database using JSP? [5]

  • Use Class.forName() to dynamically load the database driver - For MySQL, use com.mysql.jdbc.Driver - For other databases, use appropriate driver class names - Use DriverManager.getConnection() with three parameters: - URL: Connection string with host, port, and database name - Username: Databas...
Open this answer on its own page →

Handling multiple result sets

2082 · 5 marks

How do you handle multiple results in JDBC? Explain. [5]

Show solved answer

Handling Multiple Results in JDBC

Answer

Handling multiple results in JDBC involves managing situations where a single SQL statement execution returns more than one result set. This typically occurs with stored procedures or batch operations. Here's how to handle them:

1. Using execute() Method

The execute() method returns a boolean indicating whether the first result is a ResultSet:

Statement stmt = connection.createStatement();
boolean isResultSet = stmt.execute(sqlQuery);

if (isResultSet) {
    ResultSet rs = stmt.getResultSet();
    // Process first result set
} else {
    int updateCount = stmt.getUpdateCount();
    // Process update count
}

2. Processing Multiple Result Sets

Use getMoreResults() to move through subsequent result sets:

Statement stmt = connection.createStatement();
stmt.execute(sqlQuery);

int resultIndex = 0;
while (true) {
    ResultSet rs = stmt.getResultSet();
    if (rs != null) {
        // Process current result set
        while (rs.next()) {
            // Handle row data
        }
        resultIndex++;
    }
    
    // Move to next result
    if (!stmt.getMoreResults()) {
        break;
    }
}

3. Handling Update Counts

Distinguish between result sets and update counts:

int result = stmt.getUpdateCount();
if (result == -1) {
    // No more results
} else if (result == 0) {
    // Update/Insert/Delete executed
} else {
    // Number of rows affected
}

4. Key Methods

MethodPurpose
execute()Returns true if result is ResultSet, false if update count
getResultSet()Retrieves current ResultSet
getUpdateCount()Gets number of rows affected
getMoreResults()Moves to next result; returns true if ResultSet exists

5. Best Practice

Always close resources properly:

try {
    // Process multiple results
} finally {
    if (rs != null) rs.close();
    if (stmt != null) stmt.close();
}

This approach ensures efficient handling of complex SQL operations returning multiple result sets.

Open this answer on its own page →

Type 0 JDBC driver

2082 · 5 marks

What is Type 0 JDBC driver? Discuss about UDP. [5]

Show solved answer

Model Answer: Type 0 JDBC Driver and UDP

Type 0 JDBC Driver

Type 0 JDBC Driver (also called the JDBC-ODBC Bridge Driver) is a bridge-based driver that acts as a middleware between Java applications and databases through ODBC (Open Database Connectivity).

Key Characteristics:

  • Architecture: Uses ODBC drivers installed on the client machine to communicate with the database
  • Connection Path: Java Application → JDBC Driver → ODBC Driver → Database
  • Platform Dependency: Requires ODBC drivers to be installed and configured on the client system
  • Performance: Slower due to multiple layers of translation and bridging
  • Usage: Primarily used for legacy systems and when ODBC drivers are already available

Limitations:

  • Not suitable for web applications (ODBC not available on web servers)
  • Performance overhead from bridge translation
  • Deprecated in modern Java versions (removed from Java 8 onwards)

UDP (User Datagram Protocol)

UDP is a connectionless, unreliable transport layer protocol (Layer 4 of OSI model) used for fast data transmission.

Key Characteristics:

FeatureDetails
ConnectionConnectionless - no handshake required
ReliabilityUnreliable - no guarantee of delivery
OrderingPackets may arrive out of order
SpeedFast transmission with minimal overhead
Header Size8 bytes (smaller than TCP)
Flow ControlNo flow control mechanism

Applications:

  • Video/audio streaming
  • Online gaming
  • DNS queries
  • VoIP
  • Real-time applications where speed matters more than reliability

Advantages:

  • Low latency and overhead
  • Suitable for real-time communication
  • Broadcast and multicast capable

Disadvantages:

  • No error checking or retransmission
  • No congestion control
  • Packets may be lost or duplicated
Open this answer on its own page →

JDBC architecture and driver types

2081 · 5 marks

Explain the architecture of JDBC and list the JDBC driver types. [5]

JDBC (Java Database Connectivity) follows a layered architecture consisting of two main layers: - This is the top layer where Java applications interact with databases - Applications use JDBC API to communicate with databases - Developers write code using JDBC interfaces and classes - This layer ...

Open this answer on its own page →

Differences between Statement and PreparedStatement

2080 · 5 marks

How prepared statements differs from statements? Explain use of prepared statements with example. [5]

Aspect Statement Prepared Statement -------------------------------------- Compilation SQL query compiled every time it executes SQL query pre-compiled once, reused multiple times Performance Slower for repeated queries Faster for repeated queries SQL Injection Vulnerable to SQL injection attacks...

Open this answer on its own page →

Steps of JDBC connection

0 · 5 marks

Explain steps of JDBC with suitable example. [5]

JDBC is a Java API that allows Java programs to interact with databases. The main steps are: Register the database driver class with the DriverManager. Create a connection to the database using the connection URL, username, and password. Create a Statement object to execute SQL queries. Execute S...

Open this answer on its own page →