Connecting to Databases with JDBC

In this exercise, you will learn how to connect your Java application to a database using JDBC (Java Database Connectivity). Through this exercise, you will execute SQL queries, manage database connections, and manipulate results obtained from a database in your Java application, improving your skills in database interaction within the Java programming environment.



Topic

Databases and JDBC

Java Exercise

In this exercise, you will create a Java program that connects to a database using JDBC. First, you will configure the database connection and then execute an SQL query to retrieve data from a specific table. You will then process the query results and display them in the console. Throughout the exercise, you will learn how to handle exceptions and properly close connections to ensure the application runs smoothly.

Instructions:

  1. Configure a database connection using JDBC.
  2. Execute an SQL query to retrieve data from a table.
  3. Iterate over the query results and display the data to the console.
  4. Handle any database-related exceptions.
  5. Make sure to properly close the connection, the Statement, and the ResultSet.

This exercise will help you understand how to use JDBC to interact with databases in Java, an essential skill for enterprise applications that rely on storing and retrieving data from relational databases.


import java.sql.*;

public class ConnectDatabase {

    public static void main(String[] args) {
        // Database URL, user, and password
        String url = "jdbc:mysql://localhost:3306/my_database";
        String user = "root";
        String password = "my_password";

        // Establish the connection to the database
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            connection = DriverManager.getConnection(url, user, password);
            System.out.println("Successful connection to the database.");

            // Create an SQL query
            String query = "SELECT * FROM employees";
            statement = connection.createStatement();
            resultSet = statement.executeQuery(query);

            // Iterate over the results
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String position = resultSet.getString("position");

                // Display the data
                System.out.println("ID: " + id + ", Name: " + name + ", Position: " + position);
            }
        } catch (SQLException e) {
            System.out.println("Connection or query error: " + e.getMessage());
        } finally {
            // Explicitly close the resources
            try {
                if (resultSet != null) resultSet.close();
                if (statement != null) statement.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                System.out.println("Error closing resources: " + e.getMessage());
            }
        }
    }
}

 Output:

Successful connection to the database.
ID: 1, Name: Juan Perez, Position: Manager
ID: 2, Name: Ana Lopez, Position: Developer
ID: 3, Name: Luis Gomez, Position: Administrator

This program demonstrates how to connect a Java application to a database using JDBC. The connection is established via the database URL, username, and password. An SQL query is then executed to retrieve data from the employees table, and the results are displayed in the console. The use of try-with-resources ensures that resources such as the connection, statement, and result set are automatically closed after use.


 Share this JAVA exercise