JDBC Connection Interface Example with MySQL Database

In this tutorial, we will explore how to use the JDBC Connection interface to interact with a MySQL database. The Connection interface is a part of the JDBC API and represents a connection to a specific database. It provides methods for executing SQL queries, obtaining metadata, managing transactions, and more.

Introduction

What is JDBC?

Java Database Connectivity (JDBC) is an API that enables Java applications to interact with databases. It provides methods to query and update data in a database, as well as to retrieve metadata about the database itself.

What is the Connection Interface?

The Connection interface is a crucial part of the JDBC API. It represents a single database connection that provides various methods to execute SQL statements, manage transactions, and retrieve metadata about the database. The Connection interface also supports managing transactions by allowing the developer to commit and roll back transactions.

Key Features of the Connection Interface

  1. Executing SQL Statements: The Connection interface provides methods to create Statement, PreparedStatement, and CallableStatement objects for executing SQL queries.
  2. Transaction Management: It allows you to manage transactions by committing or rolling back changes.
  3. Metadata Retrieval: You can retrieve metadata about the database and the results of SQL queries.
  4. Connection Pooling: The Connection interface supports connection pooling, which can improve the performance of database applications.
  5. Auto-commit Mode: It supports setting the auto-commit mode for the connection, which determines whether changes are committed automatically after each SQL statement.

Table of Contents

  1. Setting Up the MySQL Database
  2. Establishing a Database Connection
  3. Executing SQL Queries
  4. Managing Transactions
  5. Retrieving Database Metadata
  6. Closing the Connection
  7. Conclusion

1. Setting Up the MySQL Database

First, create a database named jdbc_example and a products table within it. Open your MySQL command line or any MySQL client and execute the following commands:

CREATE DATABASE jdbc_example;

USE jdbc_example;

CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    description VARCHAR(255),
    price DECIMAL(10, 2)
);

2. Establishing a Database Connection

We will start by establishing a connection to the MySQL database using JDBC.

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

public class JDBCExample {
    private static final String URL = "jdbc:mysql://localhost:3306/jdbc_example";
    private static final String USER = "root";
    private static final String PASSWORD = "password";

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

    public static void main(String[] args) {
        try (Connection connection = getConnection()) {
            if (connection != null) {
                System.out.println("Connected to the database!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

3. Executing SQL Queries

We can use the Connection interface to create a Statement object and execute SQL queries. Here, we will insert a record into the products table.

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class InsertProductExample {
    public static void main(String[] args) {
        String insertSQL = "INSERT INTO products (name, description, price) VALUES ('Laptop', 'Dell Inspiron', 75000.00)";

        try (Connection connection = JDBCExample.getConnection();
             Statement statement = connection.createStatement()) {
            int rowsInserted = statement.executeUpdate(insertSQL);
            System.out.println(rowsInserted + " row(s) inserted!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

4. Managing Transactions

We can manage transactions using the Connection interface by setting auto-commit to false, and then explicitly committing or rolling back the transaction.

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class TransactionExample {
    public static void main(String[] args) {
        String updateSQL = "UPDATE products SET price = 70000.00 WHERE name = 'Laptop'";

        try (Connection connection = JDBCExample.getConnection();
             Statement statement = connection.createStatement()) {

            connection.setAutoCommit(false);  // Disable auto-commit mode

            int rowsUpdated = statement.executeUpdate(updateSQL);

            // Commit the transaction
            connection.commit();
            System.out.println(rowsUpdated + " row(s) updated!");

        } catch (SQLException e) {
            e.printStackTrace();
            try (Connection connection = JDBCExample.getConnection()) {
                connection.rollback();  // Rollback the transaction on error
                System.out.println("Transaction rolled back.");
            } catch (SQLException rollbackException) {
                rollbackException.printStackTrace();
            }
        }
    }
}

5. Retrieving Database Metadata

We can use the Connection interface to retrieve metadata about the database.

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

public class MetadataExample {
    public static void main(String[] args) {
        try (Connection connection = JDBCExample.getConnection()) {
            DatabaseMetaData metaData = connection.getMetaData();

            String databaseProductName = metaData.getDatabaseProductName();
            String databaseProductVersion = metaData.getDatabaseProductVersion();
            String driverName = metaData.getDriverName();
            String driverVersion = metaData.getDriverVersion();
            String url = metaData.getURL();
            String userName = metaData.getUserName();

            System.out.println("Database Product Name: " + databaseProductName);
            System.out.println("Database Product Version: " + databaseProductVersion);
            System.out.println("Driver Name: " + driverName);
            System.out.println("Driver Version: " + driverVersion);
            System.out.println("URL: " + url);
            System.out.println("User Name: " + userName);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

6. Closing the Connection

Using the try-with-resources statement ensures that the connection is closed automatically. This is important to free up database resources.

import java.sql.Connection;
import java.sql.SQLException;

public class CloseConnectionExample {
    public static void main(String[] args) {
        try (Connection connection = JDBCExample.getConnection()) {
            if (connection != null) {
                System.out.println("Connected to the database!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Conclusion

In this tutorial, we have covered the basics of using the JDBC Connection interface to interact with a MySQL database. We demonstrated how to establish a connection, execute SQL queries, manage transactions, retrieve metadata, and close the connection using the try-with-resources statement. This guide should help you get started with JDBC and understand how to use the Connection interface effectively.

Comments