DBMS Week-8 Assignment
DBMS Week-8 Assignment
databases. It provides methods for querying and updating data in a database, enabling Java
applications to connect to virtually any kind of relational database, such as MySQL, Oracle,
PostgreSQL, etc. JDBC acts as a bridge between Java applications and database management systems
(DBMS).
JDBC works by using drivers, which are Java classes that implement the JDBC API. Each database
vendor provides a JDBC driver that allows Java applications to communicate with its database in a
standard way. When a Java application sends SQL statements through JDBC, the driver translates
these requests into a format that the DBMS can understand, executes them, and returns the results.
1. Load the JDBC Driver: The driver is required to establish communication with the database.
Loading it enables the Java application to interact with the database.
This line dynamically loads the driver class. For modern JDBC (Java 6 and above), the driver is
automatically loaded when the connection URL is specified, so this step is often optional.
4. Execute the Query: Use the Statement object to execute queries. Queries that return a result
set (e.g., SELECT) use the executeQuery() method, while updates (e.g., INSERT, UPDATE,
DELETE) use the executeUpdate() method.
5. Process the Results: If the query returns results (e.g., with SELECT), these are stored in a
ResultSet. The data in the ResultSet can be accessed using methods like next(), getString(),
etc.
while (resultSet.next()) {
System.out.println("Username: " + resultSet.getString("username"));
6. Close the Connection: To avoid resource leaks, it’s essential to close the ResultSet,
Statement, and Connection objects when they are no longer needed.
resultSet.close();
statement.close();
connection.close();
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
while (resultSet.next()) {
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
Summary
JDBC provides a standardized way for Java applications to interact with databases by using drivers
that translate Java requests into database commands. The process involves loading the driver,
establishing a connection, creating statements, executing queries, processing results, and then
closing the connection to manage resources effectively.