JDBC: Navigating ResultSet, JDBC Exception Classes & Connecting to a Remote Database
1. Navigating the ResultSet Object Contents
When you execute a SQL SELECT query using ResultSet rs = stmt.executeQuery("SELECT * FROM students");, the database returns a virtual table of rows and columns stored inside a ResultSet object.
How the ResultSet Cursor Works:
- A
ResultSetobject maintains an internal pointer called a Cursor, which initially points just BEFORE the first row (Row 0). - Calling
rs.next()moves the cursor forward to the first row and returnstrue. When there are no more rows left,rs.next()returnsfalse!
next() / first() →getInt(1), getString("name")previous() / absolute(k) ↔last() jumps to endA. Forward-Only vs Scrollable ResultSet
By default, a ResultSet is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY (meaning the cursor can only move downward from top to bottom using next()).
To navigate backward, jump to the first/last row, or jump to any row number, we create a Scrollable ResultSet by passing type constants into conn.createStatement():
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY
);
B. Cursor Navigation Methods of ResultSet:
| Navigation Method | Description |
|---|---|
boolean next() |
Moves the cursor forward one row from its current position. Returns false after the last row. |
boolean previous() |
Moves the cursor backward one row (Requires Scrollable ResultSet). |
boolean first() |
Moves the cursor directly to the very first row of the ResultSet. |
boolean last() |
Moves the cursor directly to the very last row of the ResultSet. |
boolean absolute(int row) |
Moves the cursor directly to the specified row number (e.g., rs.absolute(5) jumps to Row 5). |
boolean relative(int rows) |
Moves the cursor a relative number of rows forward (+n) or backward (-n) from the current row. |
void beforeFirst() / afterLast() |
Positions the cursor before the first row or after the last row. |
C. Getter Methods to Read Column Values from the Current Row:
You can pass either the 1-based Column Index (1, 2, 3...) or the Column Name ("roll_no", "name"):
rs.getInt(1)orrs.getInt("roll_no")— Reads an integer column.rs.getString(2)orrs.getString("name")— Reads aVARCHAR/ text column.rs.getDouble("cgpa")— Reads a decimal/floating-point column.rs.getDate("dob")— Reads a SQLDATEcolumn.
2. The JDBC Exception Classes (SQLException & Subclasses)
Whenever an error occurs while interacting with a database (such as wrong database password, invalid SQL syntax, duplicate primary key, or lost network connection to the DB server), JDBC throws a Checked Exception from the java.sql package.
•
SQLWarning: Non-fatal database warnings retrieved via getWarnings()•
DataTruncation: Data value was unexpectedly cut off
Thrown when one of the SQL commands fails during a batch update (
executeBatch())
1. java.sql.SQLException
The core exception class that provides information on any database access error. Every SQLException object contains three crucial pieces of diagnostic information:
String getMessage(): Returns a human-readable description of the error (e.g.,"Table 'college.students' doesn't exist").String getSQLState(): Returns a 5-character standard X/Open or SQL:2003 code identifying the error category (e.g.,"42S02"for missing table,"28000"for invalid password).int getErrorCode(): Returns the database vendor’s specific integer error code (e.g., MySQL Error1045for Access Denied).SQLException getNextException(): Chains to the nextSQLExceptionif multiple errors occurred together.
catch (SQLException e) {
System.out.println("Error Message : " + e.getMessage());
System.out.println("SQLState Code : " + e.getSQLState());
System.out.println("Vendor Code : " + e.getErrorCode());
}
2. SQLWarning
- A subclass of
SQLExceptionthat represents non-fatal database warnings. Unlike normal exceptions,SQLWarningdoes not halt program execution; you can inspect warnings on aConnection,Statement, orResultSetusing.getWarnings().
3. BatchUpdateException
- Thrown when an error occurs during a batch update operation (
stmt.executeBatch()). ItsgetUpdateCounts()method tells you which queries in the batch succeeded before the failure occurred.
3. Connecting to a Remote Database (The 7 Standard JDBC Steps)
Connecting a Java program to a Remote Database (a MySQL or Oracle database server hosted on another machine over a LAN or the Internet, e.g., at IP 192.168.1.50:3306 or db.campusnotes.in:3306) is identical to connecting locally—you simply specify the Remote Server’s IP Address / Domain Name and Port Number inside the JDBC Connection URL!
Format of a Remote JDBC Connection URL:
jdbc:mysql://192.168.1.50:3306/davv_db
├─ Protocol & Driver : jdbc:mysql
├─ Remote Server IP : 192.168.1.50
├─ DB Port : 3306
└─ Database Name : davv_db
The 7 Steps to Connect to a Database in Java (Memorize in Order!):
- Step 1: Import the
java.sql.*package (import java.sql.*;). - Step 2: Load and Register the JDBC Driver (
Class.forName("com.mysql.cj.jdbc.Driver");). - Step 3: Establish the Connection to the Remote Database using
DriverManager.getConnection(url, user, password). - Step 4: Create a
StatementorPreparedStatementobject (conn.createStatement()). - Step 5: Execute the SQL Query (
stmt.executeQuery(...)orstmt.executeUpdate(...)). - Step 6: Process and Navigate the
ResultSet(while (rs.next()) { ... }). - Step 7: Close the
ResultSet,Statement, andConnection(conn.close()).
Complete Program: Connecting to a Remote Database & Navigating ResultSet
// STEP 1: Import the java.sql package
import java.sql.*;
public class RemoteDatabaseDemo {
public static void main(String[] args) {
// Remote Database Server IP (e.g., 192.168.1.50), Port 3306, Database: "davv_bca"
String remoteUrl = "jdbc:mysql://192.168.1.50:3306/davv_bca";
String dbUser = "bca_admin";
String dbPass = "Indore@2026";
try {
// STEP 2: Load and Register the MySQL Type-4 JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("JDBC Driver Loaded Successfully!");
// STEP 3: Establish Connection to the Remote Database Server
Connection conn = DriverManager.getConnection(remoteUrl, dbUser, dbPass);
System.out.println("Connected to Remote Database at 192.168.1.50!");
// STEP 4: Create a Scrollable Statement Object
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY
);
// STEP 5: Execute SELECT Query on Remote Database
String sql = "SELECT roll_no, name, cgpa FROM students";
ResultSet rs = stmt.executeQuery(sql);
// STEP 6: Navigate the ResultSet Forward using next()
System.out.println("\n--- All Student Records (Forward Navigation) ---");
while (rs.next()) {
int roll = rs.getInt("roll_no");
String name = rs.getString("name");
double cgpa = rs.getDouble("cgpa");
System.out.println("Roll: " + roll + " | Name: " + name + " | CGPA: " + cgpa);
}
// Demonstrate Scrollable Navigation (Jumping directly to First & Last Row)
if (rs.first()) {
System.out.println("\nFirst Student in Table : " + rs.getString("name"));
}
if (rs.last()) {
System.out.println("Last Student in Table : " + rs.getString("name"));
}
// STEP 7: Close all Database Resources
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
System.out.println("Driver JAR missing: " + e.getMessage());
} catch (SQLException e) {
// Handling JDBC Exception using SQLException methods
System.out.println("Database Error : " + e.getMessage());
System.out.println("SQLState : " + e.getSQLState());
System.out.println("Error Code : " + e.getErrorCode());
}
}
}
💡 Exam Preparation Tips for DAVV BCA
- Writing the 7 numbered JDBC steps along with the complete program above is a guaranteed way to score 8/8 marks on any JDBC question!
- Don’t forget to mention the 3 diagnostic methods of
SQLException:getMessage(),getSQLState(), andgetErrorCode().