Java JDBC (Database Connectivity) Practice Questions with Solutions

JDBC (Java Database Connectivity) is a Java API that allows Java applications to communicate with relational databases such as MySQL, Oracle, SQL Server, and PostgreSQL.

Using JDBC, developers can:

  • Connect Java applications to databases
  • Insert records
  • Retrieve records
  • Update existing data
  • Delete records
  • Execute SQL queries

JDBC is one of the most important topics for Core Java, Advanced Java, Spring Boot, and Java Backend Development. Java JDBC (Database Connectivity) Practice questions with solutions help to understand the concepts.


What is JDBC?

JDBC stands for Java Database Connectivity.

It is a standard Java API provided by Oracle for connecting Java applications with databases.

Using JDBC, Java applications can perform CRUD operations:

  • Create
  • Read
  • Update
  • Delete

Why Do We Need JDBC?

Most real-world applications store data inside databases.

Examples:

  • Student Management System
  • Banking Software
  • Hospital Management System
  • Inventory Management
  • E-commerce Website
  • Online Ticket Booking
  • Employee Management System

Without JDBC, Java programs cannot communicate with these databases.


JDBC Architecture

Java Application
        │
        │
      JDBC API
        │
        │
   JDBC Driver
        │
        │
     Database

JDBC Driver Types

Java supports four types of JDBC drivers:

  1. JDBC-ODBC Bridge Driver (Deprecated)
  2. Native Driver
  3. Network Protocol Driver
  4. Thin Driver (Most Common)

For MySQL, the MySQL Connector/J (Thin Driver) is commonly used.


JDBC Steps

A typical JDBC program follows these steps:

  1. Import JDBC packages.
  2. Load the JDBC driver.
  3. Establish a database connection.
  4. Create a statement.
  5. Execute SQL queries.
  6. Process the results.
  7. Close the connection.

Required Package

import java.sql.*;

MySQL JDBC Driver

To connect Java with MySQL, include the MySQL Connector/J library in your project.

Example driver class:

com.mysql.cj.jdbc.Driver

Connection URL

jdbc:mysql://localhost:3306/studentdb

Where:

  • localhost → Database server
  • 3306 → Default MySQL port
  • studentdb → Database name

Real-World Applications

JDBC is widely used in:

  • Banking Applications
  • Hospital Software
  • Payroll Systems
  • CRM Applications
  • ERP Software
  • School Management Systems
  • Spring Boot Applications
  • Enterprise Java Projects

Before Learning This Chapter

You should already understand:

  • Java Classes
  • Objects
  • Exception Handling
  • File Handling
  • Collections Framework

Basic SQL knowledge is also recommended.


1. Java Program to Load the JDBC Driver

Problem Statement

Write a Java program to load the MySQL JDBC driver.

Java Solution

public class Main {

    public static void main(String[] args) {

        try {

            Class.forName("com.mysql.cj.jdbc.Driver");

            System.out.println("Driver Loaded Successfully");

        }

        catch (ClassNotFoundException exception) {

            System.out.println(exception);

        }

    }

}

Sample Output

Driver Loaded Successfully

Explanation

The Class.forName() method loads the JDBC driver into memory.

If the driver is not found, Java throws a ClassNotFoundException.

Concepts Covered

  • JDBC Driver
  • Class.forName()
  • Exception Handling
  • JDBC API

2. Java Program to Establish a Database Connection

Problem Statement

Write a Java program to connect to a MySQL database.

Java Solution

import java.sql.Connection;
import java.sql.DriverManager;

public class Main {

    public static void main(String[] args) {

        try {

            Connection connection = DriverManager.getConnection(

                "jdbc:mysql://localhost:3306/studentdb",

                "root",

                "password"

            );

            System.out.println("Database Connected Successfully");

            connection.close();

        }

        catch (Exception exception) {

            System.out.println(exception);

        }

    }

}

Sample Output

Database Connected Successfully

Explanation

DriverManager.getConnection() establishes a connection between the Java application and the database.

Parameters:

  • Database URL
  • Username
  • Password

Always close the connection after completing database operations.

Concepts Covered

  • DriverManager
  • Connection
  • Database URL
  • Database Connectivity

3. Java Program to Create a Statement Object

Problem Statement

Write a Java program to create a Statement object after connecting to a database.

Java Solution

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Main {

    public static void main(String[] args) {

        try {

            Connection connection = DriverManager.getConnection(

                "jdbc:mysql://localhost:3306/studentdb",

                "root",

                "password"

            );

            Statement statement = connection.createStatement();

            System.out.println("Statement Created Successfully");

            statement.close();

            connection.close();

        }

        catch (Exception exception) {

            System.out.println(exception);

        }

    }

}

Sample Output

Statement Created Successfully

Explanation

A Statement object is used to execute SQL queries.

Common methods:

  • executeQuery()
  • executeUpdate()
  • execute()

It acts as a bridge between the Java application and the database.

Concepts Covered

  • Statement
  • createStatement()
  • JDBC Statement
  • SQL Execution

4. Java Program to Insert Data into a Database

Problem Statement

Write a Java program to insert a new record into a MySQL database using a Statement object.

Java Solution

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Main {

    public static void main(String[] args) {

        try {

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/studentdb",

                    "root",

                    "password"

            );

            Statement statement = connection.createStatement();

            String query = "INSERT INTO students VALUES (101,'Rahul',85)";

            int rows = statement.executeUpdate(query);

            System.out.println(rows + " Record Inserted Successfully");

            statement.close();

            connection.close();

        }

        catch (Exception exception) {

            System.out.println(exception);

        }

    }

}

Sample Output

1 Record Inserted Successfully

Explanation

The executeUpdate() method is used for SQL statements that modify the database, such as:

  • INSERT
  • UPDATE
  • DELETE
  • CREATE TABLE
  • DROP TABLE

It returns the number of affected rows.

In this example, one student record is inserted into the students table.

Concepts Covered

  • INSERT Statement
  • executeUpdate()
  • Statement Object
  • JDBC CRUD Operations

5. Java Program to Retrieve Data from a Database

Problem Statement

Write a Java program to retrieve and display records from a MySQL database.

Java Solution

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {

    public static void main(String[] args) {

        try {

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/studentdb",

                    "root",

                    "password"

            );

            Statement statement = connection.createStatement();

            String query = "SELECT * FROM students";

            ResultSet result = statement.executeQuery(query);

            while (result.next()) {

                System.out.println(

                        result.getInt("id") + " "

                                + result.getString("name") + " "

                                + result.getInt("marks")

                );

            }

            result.close();

            statement.close();

            connection.close();

        }

        catch (Exception exception) {

            System.out.println(exception);

        }

    }

}

Sample Output

101 Rahul 85
102 Amit 90
103 Neha 88

Explanation

The executeQuery() method is used to execute SELECT statements.

It returns a ResultSet object containing the retrieved records.

The next() method moves the cursor to the next row until all rows have been processed.

The values are accessed using methods such as:

getInt()

getString()

getDouble()

depending on the column’s data type.

Concepts Covered

  • SELECT Statement
  • executeQuery()
  • ResultSet
  • next()
  • Retrieving Database Records

6. Java Program to Update Records in a Database

Problem Statement

Write a Java program to update an existing record in a MySQL database.

Java Solution

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Main {

    public static void main(String[] args) {

        try {

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/studentdb",

                    "root",

                    "password"

            );

            Statement statement = connection.createStatement();

            String query = "UPDATE students SET marks = 95 WHERE id = 101";

            int rows = statement.executeUpdate(query);

            System.out.println(rows + " Record Updated Successfully");

            statement.close();

            connection.close();

        }

        catch (Exception exception) {

            System.out.println(exception);

        }

    }

}

Sample Output

1 Record Updated Successfully

Explanation

The UPDATE statement modifies existing records in a database.

The executeUpdate() method returns the number of updated rows.

Always use a WHERE clause to avoid updating every record in the table.

Concepts Covered

  • UPDATE Statement
  • executeUpdate()
  • JDBC CRUD Operations
  • Statement

7. Java Program to Delete Records from a Database

Problem Statement

Write a Java program to delete a record from a MySQL database.

Java Solution

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Main {

    public static void main(String[] args) {

        try {

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/studentdb",

                    "root",

                    "password"

            );

            Statement statement = connection.createStatement();

            String query = "DELETE FROM students WHERE id = 101";

            int rows = statement.executeUpdate(query);

            System.out.println(rows + " Record Deleted Successfully");

            statement.close();

            connection.close();

        }

        catch (Exception exception) {

            System.out.println(exception);

        }

    }

}

Sample Output

1 Record Deleted Successfully

Explanation

The DELETE statement removes records from a database table.

The WHERE clause ensures that only the intended record is deleted.

Without a WHERE clause, all records in the table will be removed.

Concepts Covered

  • DELETE Statement
  • executeUpdate()
  • JDBC CRUD Operations
  • Statement

8. Java Program to Use PreparedStatement

Problem Statement

Write a Java program to create and use a PreparedStatement.

Java Solution

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Main {

    public static void main(String[] args) {

        try {

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/studentdb",

                    "root",

                    "password"

            );

            String query = "INSERT INTO students VALUES (?, ?, ?)";

            PreparedStatement statement = connection.prepareStatement(query);

            statement.setInt(1, 101);

            statement.setString(2, "Rahul");

            statement.setInt(3, 90);

            statement.executeUpdate();

            System.out.println("Record Inserted Successfully");

            statement.close();

            connection.close();

        }

        catch (Exception exception) {

            System.out.println(exception);

        }

    }

}

Sample Output

Record Inserted Successfully

Explanation

PreparedStatement is preferred over Statement because it:

  • Improves performance
  • Prevents SQL Injection attacks
  • Supports parameterized queries
  • Makes code easier to maintain

The ? symbols act as placeholders for values that are supplied later.

Concepts Covered

  • PreparedStatement
  • Parameterized Queries
  • SQL Injection Prevention
  • JDBC API

9. Java Program to Insert Records Using PreparedStatement

Problem Statement

Write a Java program to insert student details into a database using PreparedStatement.

Java Solution

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Main {

    public static void main(String[] args) {

        try {

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/studentdb",

                    "root",

                    "password"

            );

            String query = "INSERT INTO students(id, name, marks) VALUES (?, ?, ?)";

            PreparedStatement statement = connection.prepareStatement(query);

            statement.setInt(1, 102);

            statement.setString(2, "Amit");

            statement.setInt(3, 88);

            int rows = statement.executeUpdate();

            System.out.println(rows + " Record Inserted");

            statement.close();

            connection.close();

        }

        catch (Exception exception) {

            System.out.println(exception);

        }

    }

}

Sample Output

1 Record Inserted

Explanation

The values are safely passed to the SQL query using setter methods such as:

  • setInt()
  • setString()
  • setDouble()

This approach is secure and widely used in enterprise applications.

Concepts Covered

  • PreparedStatement
  • INSERT Operation
  • Parameter Binding
  • JDBC CRUD

10. Java Program to Retrieve Records Using PreparedStatement

Problem Statement

Write a Java program to retrieve a student record using PreparedStatement.

Java Solution

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Main {

    public static void main(String[] args) {

        try {

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/studentdb",

                    "root",

                    "password"

            );

            String query = "SELECT * FROM students WHERE id = ?";

            PreparedStatement statement = connection.prepareStatement(query);

            statement.setInt(1, 102);

            ResultSet result = statement.executeQuery();

            while (result.next()) {

                System.out.println(

                        result.getInt("id") + " "

                                + result.getString("name") + " "

                                + result.getInt("marks")

                );

            }

            result.close();

            statement.close();

            connection.close();

        }

        catch (Exception exception) {

            System.out.println(exception);

        }

    }

}

Sample Output

102 Amit 88

Explanation

PreparedStatement is used with a parameterized SELECT query.

The parameter value is assigned using:

statement.setInt(1, 102);

The query returns a ResultSet, which is processed row by row using the next() method.

Concepts Covered

  • PreparedStatement
  • SELECT Query
  • ResultSet
  • Parameterized Queries
  • Secure Database Access

11. Java Program to Create a Database Table Using JDBC

Problem Statement

Write a Java program to create a table in a MySQL database using JDBC.

Java Solution

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Main {

    public static void main(String[] args) {

        try {

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/studentdb",

                    "root",

                    "password"

            );

            Statement statement = connection.createStatement();

            String query =
                    "CREATE TABLE students (" +
                    "id INT PRIMARY KEY," +
                    "name VARCHAR(50)," +
                    "marks INT" +
                    ")";

            statement.executeUpdate(query);

            System.out.println("Table Created Successfully");

            statement.close();

            connection.close();

        }

        catch (Exception exception) {

            System.out.println(exception);

        }

    }

}

Sample Output

Table Created Successfully

Explanation

The CREATE TABLE SQL statement creates a new table in the database.

The executeUpdate() method executes DDL (Data Definition Language) statements such as:

  • CREATE
  • ALTER
  • DROP

Concepts Covered

  • CREATE TABLE
  • Statement
  • executeUpdate()
  • JDBC DDL Operations

12. Java Program to Perform Batch Processing

Problem Statement

Write a Java program to insert multiple records into a database using JDBC batch processing.

Java Solution

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Main {

    public static void main(String[] args) {

        try {

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/studentdb",

                    "root",

                    "password"

            );

            Statement statement = connection.createStatement();

            statement.addBatch(
                    "INSERT INTO students VALUES (101,'Rahul',90)"
            );

            statement.addBatch(
                    "INSERT INTO students VALUES (102,'Amit',85)"
            );

            statement.addBatch(
                    "INSERT INTO students VALUES (103,'Neha',95)"
            );

            statement.executeBatch();

            System.out.println("Batch Executed Successfully");

            statement.close();

            connection.close();

        }

        catch (Exception exception) {

            System.out.println(exception);

        }

    }

}

Sample Output

Batch Executed Successfully

Explanation

Batch processing allows multiple SQL statements to execute together instead of one by one.

Advantages:

  • Faster execution
  • Reduced database communication
  • Better performance

Useful for:

  • Payroll Systems
  • Bulk Student Imports
  • Inventory Updates
  • Banking Applications

Concepts Covered

  • addBatch()
  • executeBatch()
  • Batch Processing
  • JDBC Performance

13. Java Program to Demonstrate JDBC Transactions

Problem Statement

Write a Java program to demonstrate transaction management using JDBC.

Java Solution

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Main {

    public static void main(String[] args) {

        try {

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/studentdb",

                    "root",

                    "password"

            );

            connection.setAutoCommit(false);

            Statement statement = connection.createStatement();

            statement.executeUpdate(
                    "INSERT INTO students VALUES (104,'Priya',88)"
            );

            statement.executeUpdate(
                    "INSERT INTO students VALUES (105,'Rohit',92)"
            );

            connection.commit();

            System.out.println("Transaction Completed Successfully");

            statement.close();

            connection.close();

        }

        catch (Exception exception) {

            System.out.println(exception);

        }

    }

}

Sample Output

Transaction Completed Successfully

Explanation

A transaction groups multiple SQL statements into one logical unit.

Key methods:

setAutoCommit(false)

commit()

rollback()

If an error occurs before commit(), the application can call rollback() to undo all changes.

Transactions help maintain data consistency.

Concepts Covered

  • Transactions
  • commit()
  • rollback()
  • Auto Commit
  • JDBC Transactions

14. Java Program to Retrieve Database Metadata

Problem Statement

Write a Java program to retrieve metadata from a database.

Java Solution

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;

public class Main {

    public static void main(String[] args) {

        try {

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/studentdb",

                    "root",

                    "password"

            );

            DatabaseMetaData metadata = connection.getMetaData();

            System.out.println("Database : " + metadata.getDatabaseProductName());

            System.out.println("Driver : " + metadata.getDriverName());

            System.out.println("Version : " + metadata.getDatabaseProductVersion());

            connection.close();

        }

        catch (Exception exception) {

            System.out.println(exception);

        }

    }

}

Sample Output

Database : MySQL
Driver : MySQL Connector/J
Version : 8.x.x

Note: The exact version number depends on the installed MySQL server and JDBC driver.

Explanation

DatabaseMetaData provides information about:

  • Database name
  • Driver name
  • Version
  • Supported features

It is useful for building database management tools.

Concepts Covered

  • DatabaseMetaData
  • JDBC API
  • Database Information
  • Driver Information

15. Java Program to Build a Real-World Student Management System Using JDBC

Problem Statement

Write a Java program to insert and display student records using JDBC.

Java Solution

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Main {

    public static void main(String[] args) {

        try {

            Connection connection = DriverManager.getConnection(

                    "jdbc:mysql://localhost:3306/studentdb",

                    "root",

                    "password"

            );

            String insertQuery =
                    "INSERT INTO students(id,name,marks) VALUES(?,?,?)";

            PreparedStatement insert =
                    connection.prepareStatement(insertQuery);

            insert.setInt(1,106);

            insert.setString(2,"Anjali");

            insert.setInt(3,91);

            insert.executeUpdate();

            String selectQuery = "SELECT * FROM students";

            PreparedStatement select =
                    connection.prepareStatement(selectQuery);

            ResultSet result = select.executeQuery();

            while(result.next()){

                System.out.println(

                        result.getInt("id")+" "

                                +result.getString("name")+" "

                                +result.getInt("marks")

                );

            }

            result.close();

            insert.close();

            select.close();

            connection.close();

        }

        catch(Exception exception){

            System.out.println(exception);

        }

    }

}

Sample Output

101 Rahul 90
102 Amit 85
103 Neha 95
106 Anjali 91

Note: The displayed records depend on the data already stored in your students table.

Explanation

This program demonstrates a simple Student Management System by:

  • Connecting to the database
  • Inserting a student record
  • Retrieving all student records
  • Displaying the results

This pattern forms the foundation of many real-world applications, including:

  • School Management Systems
  • College ERP Software
  • Employee Management Systems
  • Customer Management Systems

Concepts Covered

  • JDBC Connection
  • PreparedStatement
  • ResultSet
  • CRUD Operations
  • Real-World Database Application

Chapter Summary

In this chapter, you learned the fundamentals of Java JDBC (Java Database Connectivity), which enables Java applications to interact with relational databases such as MySQL, Oracle, PostgreSQL, and SQL Server.

You explored how to establish database connections, execute SQL queries, perform CRUD (Create, Read, Update, Delete) operations, use Statement and PreparedStatement, process query results with ResultSet, manage transactions, perform batch processing, and retrieve database metadata.

You also built a simple Student Management System using JDBC to understand how database connectivity is applied in real-world Java applications.

Throughout this chapter, you covered:

  • Introduction to JDBC
  • JDBC Architecture
  • JDBC Driver
  • Database Connection
  • Statement
  • PreparedStatement
  • ResultSet
  • INSERT Operation
  • SELECT Operation
  • UPDATE Operation
  • DELETE Operation
  • CREATE TABLE
  • Batch Processing
  • Transactions
  • Database Metadata
  • Student Management System

These concepts form the foundation of Java backend development and are extensively used in enterprise applications, Spring Boot projects, and web-based systems.


Key Takeaways

  • JDBC allows Java applications to communicate with relational databases.
  • The JDBC workflow includes loading the driver, creating a connection, executing SQL queries, processing results, and closing resources.
  • Statement executes static SQL queries.
  • PreparedStatement is preferred because it improves performance and protects against SQL injection attacks.
  • ResultSet stores and retrieves records returned by SELECT queries.
  • CRUD operations are the core of database programming.
  • Batch processing improves performance by executing multiple SQL statements together.
  • Transactions ensure data consistency using commit() and rollback().
  • Metadata provides useful information about the database and JDBC driver.
  • Always close JDBC resources to prevent memory leaks.

Frequently Asked Questions (FAQs)

1. What is JDBC?

JDBC (Java Database Connectivity) is a standard Java API that allows Java applications to connect to relational databases and execute SQL queries.


2. What are the main steps in JDBC?

The basic JDBC workflow is:

  1. Import JDBC packages.
  2. Load the JDBC driver.
  3. Create a database connection.
  4. Create a Statement or PreparedStatement.
  5. Execute SQL queries.
  6. Process the results.
  7. Close all resources.

3. What is the difference between Statement and PreparedStatement?

StatementPreparedStatement
Executes static SQL queriesExecutes parameterized SQL queries
SlowerFaster
Vulnerable to SQL injectionPrevents SQL injection
Suitable for simple queriesRecommended for production applications

4. What is a ResultSet?

A ResultSet stores the records returned by a SELECT query.

Example:

ResultSet result = statement.executeQuery(query);

while(result.next()){

    System.out.println(result.getString("name"));

}

5. What is SQL Injection?

SQL Injection is a security vulnerability where attackers manipulate SQL queries using malicious input.

Using PreparedStatement prevents SQL injection by treating input values as data rather than executable SQL.


6. What is Batch Processing in JDBC?

Batch processing executes multiple SQL statements together, improving performance and reducing communication with the database.

Common methods:

addBatch()

executeBatch()

7. What are JDBC Transactions?

Transactions group multiple SQL operations into a single logical unit.

Important methods:

  • setAutoCommit(false)
  • commit()
  • rollback()

Transactions ensure that all operations succeed together or fail together, maintaining database consistency.


8. Where is JDBC used in real-world applications?

JDBC is widely used in:

  • Banking Systems
  • Hospital Management Software
  • School and College ERP Systems
  • Employee Management Systems
  • Inventory Management Applications
  • CRM Software
  • E-commerce Platforms
  • Spring Boot Applications
  • Enterprise Java Applications

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top