The following text modernizes the description for Java SE 17+ and focuses on the first major step: establishing a reliable and secure database connection.
OverviewWhenever a Java application interacts with a database, it performs three primary operations:
Connection object.ResultSet to retrieve and display results.
This lesson focuses on the first operation — how to connect a Java program to a relational database system using the java.sql API. In the upcoming lessons, you will see how SQL statements are issued and how results are captured.
The World Health Organization (WHO) has launched an international research initiative to gather human health data across different populations. Within this global effort, the Brazil Healthcare Administration Intranet serves as a regional system, collecting and managing hospital-level data to help identify emerging public health trends.
As part of this multidisciplinary project, you’ve joined a team of Java developers and IT consultants responsible for designing a database access layer using JDBC. Your first task is to establish a connection from the client application to the hospital database so that authorized users can view and update health information securely.
To connect and communicate with a relational database through JDBC, your program typically performs these steps:
DriverManager to open a connection to the database using a JDBC URL, username, and password.Statement or PreparedStatement object to send SQL commands.ResultSet object and close all resources when done.Here’s a minimal example showing how a Java application connects to a database using JDBC:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/healthcare";
String user = "admin";
String password = "securePass123";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connection established successfully!");
} catch (SQLException e) {
System.err.println("Error connecting to the database: " + e.getMessage());
}
}
}
The try-with-resources block ensures that the connection is closed automatically, which is critical for preventing connection leaks in enterprise systems.
After completing this module, you will be able to:
DriverManager.
In the next lesson, you will explore how JDBC translates SQL statements into database operations and how results are managed through the ResultSet interface.