Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save EhsanulHaqueSiam/073248152e4931f150b6e948e8b2d150 to your computer and use it in GitHub Desktop.
Save EhsanulHaqueSiam/073248152e4931f150b6e948e8b2d150 to your computer and use it in GitHub Desktop.
JDBC: Java Database Connectivity Installing Process and Key Informations

Introduction to JDBC

Java Database Connectivity (JDBC) is a powerful and essential technology that enables Java applications to interact with relational databases. It is a part of the Java Standard Edition (Java SE) and provides a standard API (Application Programming Interface) for connecting and executing queries on databases. JDBC allows developers to build dynamic and data-driven Java applications that can store, retrieve, and manipulate data from various database management systems (DBMS) such as MySQL, Oracle, PostgreSQL, and more.

Table of Contents:

  1. Introduction to JDBC

  2. Automated JDBC Driver Loading in Newer Versions

  3. Install Process

  4. Using JDBC and MySQL in Java

  5. Complete Demo Project with JDBC and MySQL

  6. Conclusion

History of JDBC:

JDBC was introduced as a part of the Java Development Kit (JDK) 1.1 in 1997. Its primary goal was to address the need for a standardized way to access databases from Java applications. Prior to JDBC, developers had to use proprietary database APIs, which made the process of writing database-related code cumbersome and less portable across different database systems.

JDBC Architecture:

JDBC follows a layered architecture that consists of the following key components:

  1. JDBC API: The top layer represents the API that developers use to interact with the database. It consists of interfaces and classes that define methods for establishing connections, executing queries, and processing results.

  2. Driver Manager: The Driver Manager is responsible for managing the available database drivers. It is used to load and select the appropriate driver for establishing a connection to the database.

  3. JDBC Driver: The JDBC driver is a software component that acts as a bridge between the Java application and the database. There are four types of JDBC drivers:

    • Type 1 (JDBC-ODBC Bridge): This driver uses the ODBC (Open Database Connectivity) API to connect to the database. It requires the presence of ODBC drivers on the system.

    • Type 2 (Native-API Partly Java Driver): This driver converts JDBC calls into native database API calls. It may require native libraries specific to the database system.

    • Type 3 (Network Protocol Pure Java Driver): This driver communicates with a middleware server that acts as an intermediary between the Java application and the database. It is also known as the middleware driver.

    • Type 4 (Thin Pure Java Driver): This driver communicates directly with the database using a pure Java implementation, making it the most common and popular choice for JDBC connectivity.

  4. JDBC Database: This layer represents the actual database system where data is stored and retrieved. The JDBC driver establishes a connection to the database and executes SQL statements on behalf of the Java application.

Key Steps to Use JDBC:

To use JDBC in a Java application, developers need to follow these fundamental steps:

  1. Load the JDBC Driver: Before establishing a connection to the database, the appropriate JDBC driver needs to be loaded using the Class.forName() method. For example, to load the MySQL JDBC driver, the code would be: Class.forName("com.mysql.cj.jdbc.Driver");

  2. Establish Connection: After loading the driver, a connection to the database is established using the DriverManager.getConnection() method. The connection string typically includes the database URL, username, and password.

  3. Create Statement or PreparedStatement: Once the connection is established, developers can create either a Statement or a PreparedStatement object. Statement is used for static SQL queries, whereas PreparedStatement is used for dynamic SQL queries with parameters.

  4. Execute Queries: With the Statement or PreparedStatement, developers can execute SQL queries using the executeQuery() method for SELECT statements or executeUpdate() for INSERT, UPDATE, DELETE, and other data manipulation statements.

  5. Process Results: If the query is a SELECT statement, the results are returned as a ResultSet object. Developers can process the data from the ResultSet and perform necessary actions accordingly.

  6. Close Resources: After executing the queries and processing the results, it's essential to close the ResultSet, Statement, and Connection objects to free up resources and avoid memory leaks.

Sample Code:

Here's a simple example of how to use JDBC to retrieve data from a database:

import java.sql.*;

public class JDBCSample {
    public static void main(String[] args) {
        try {
            // Load the JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish the connection
            String dbUrl = "jdbc:mysql://localhost:3306/sample_db";
            String username = "your_username";
            String password = "your_password";
            Connection conn = DriverManager.getConnection(dbUrl, username, password);

            // Create a statement
            Statement stmt = conn.createStatement();

            // Execute the query
            String sqlQuery = "SELECT * FROM employees";
            ResultSet resultSet = stmt.executeQuery(sqlQuery);

            // Process the results
            while (resultSet.next()) {
                int empId = resultSet.getInt("employee_id");
                String empName = resultSet.getString("employee_name");
                System.out.println("Employee ID: " + empId + ", Employee Name: " + empName);
            }

            // Close resources
            resultSet.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Automated JDBC Driver Loading in Newer Versions: A Seamless Database Connectivity

In the ever-evolving world of Java, advancements are continually being made to improve developer productivity and user experience. One such improvement in the realm of Java Database Connectivity (JDBC) is the automated loading of JDBC drivers in newer versions. In the past, developers had to explicitly load the JDBC driver using Class.forName(), but this manual step has been eliminated in the latest versions of JDBC. This article explores the benefits of this enhancement and provides examples to demonstrate how it simplifies the process of connecting to databases.

JDBC Driver Auto-Loading:

Traditionally, developers had to explicitly load the appropriate JDBC driver using the Class.forName() method before establishing a connection to the database. For example, to connect to a MySQL database, the code would look like this:

try {
    Class.forName("com.mysql.cj.jdbc.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample_db", "username", "password");
    // Rest of the code...
} catch (ClassNotFoundException | SQLException e) {
    e.printStackTrace();
}

In newer versions of JDBC, starting from JDBC 4.0 (included with Java SE 6), the driver loading process is automated. The JDBC API now uses the Service Provider mechanism introduced in Java 6 to locate and load drivers available in the classpath without the need for manual registration.

Service Provider Mechanism:

The Service Provider mechanism allows libraries and frameworks to extend the functionality of Java applications by providing implementations of certain interfaces through the Java Extension mechanism. The Service Provider mechanism relies on the presence of a configuration file (java.sql.Driver in our case) in the META-INF/services directory of the driver's JAR file.

The configuration file should contain the fully qualified name of the driver class. For example, the content of java.sql.Driver file inside the MySQL JDBC driver JAR would look like this:

com.mysql.cj.jdbc.Driver

When the application starts, the JVM automatically searches for these configuration files in the classpath and loads the specified classes.

Benefits of Automated JDBC Driver Loading:

  1. Simplified Code: The elimination of the manual driver loading code (Class.forName()) reduces boilerplate code, making the codebase cleaner and more maintainable.

  2. Dynamic Driver Discovery: Applications can now take advantage of multiple database drivers available in the classpath without the need to specify them explicitly, allowing for more flexibility and ease of integration with different database systems.

  3. Better Portability: The automated driver loading ensures that applications can be easily deployed across different environments without any additional configuration steps.

Examples:

Let's see how the automated JDBC driver loading works with a simple example:

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

public class JDBCSample {
    public static void main(String[] args) {
        try {
            // Establish the connection (Automated driver loading)
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample_db", "username", "password");

            // Rest of the code...

            // Close the connection
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

In this example, the DriverManager class automatically locates and loads the appropriate JDBC driver for the MySQL database using the Service Provider mechanism. The DriverManager.getConnection() method then establishes a connection to the database without any explicit driver loading code.

Installation Process

MySQL 8.0.34 vs. MySQL 8.1.0: Which One Should You Use?

MySQL is a popular open-source relational database management system used by developers and businesses worldwide to store, manage, and retrieve data efficiently. As you plan to install MySQL on your system, you might come across two versions, MySQL 8.0.34 and MySQL 8.1.0. In this article, we will guide you through the process of downloading, installing, and configuring MySQL, and we'll also discuss the differences between these versions to help you make an informed decision on which one to use.

MySQL 8.0.34:

MySQL 8.0.34 is a stable release of the MySQL 8.0 series. It is part of the MySQL Installer, which was the primary method of installing MySQL products before MySQL 8.1.0. However, the MySQL Installer has been discontinued starting from MySQL 8.1.0. This means that MySQL 8.0.34 will be the final series available through the MySQL Installer. It includes several enhancements and bug fixes to provide a robust and reliable database solution.

MySQL 8.1.0:

MySQL 8.1.0 is the first release of the MySQL 8.1 series. Starting from this version, the MySQL Installer has been replaced with MySQL product's MSI (Microsoft Installer) or Zip archive for installation. Additionally, MySQL Server 8.1 and higher now bundle MySQL Configurator, a tool that simplifies the configuration of MySQL Server settings.

It's important to note that MySQL 8.1.0 represents the latest innovations and features introduced by the MySQL development team. As with any new release, it is prudent to carefully assess the compatibility of your applications with the new version before upgrading.

Which One Should You Use?

Choosing between MySQL 8.0.34 and MySQL 8.1.0 depends on your specific requirements and considerations. If you prioritize stability and are looking for a version that has undergone extensive testing and bug fixes, MySQL 8.0.34 is a suitable choice. It has been used by the community for some time, and many production environments rely on it.

On the other hand, if you want to explore the latest features, improvements, and enhancements introduced in MySQL 8.1.0, and you are willing to accept the possible risks associated with using newer releases, then MySQL 8.1.0 might be the right choice for you.

It's essential to weigh the advantages and potential drawbacks carefully before making a decision. If you are unsure, you can try out both versions in a test environment to see which one best fits your needs.

Downloading and Installing MySQL:

Below are the step-by-step instructions to download, install, and configure MySQL, including MySQL Server, MySQL Workbench, MySQL for Visual Studio, MySQL Shell, MySQL Router, and the MySQL Connector/J for Java.

  1. Downloading MySQL:

    Visit the official MySQL downloads page:

    Click on the appropriate version to download the installer or ZIP archive.

  2. Installing MySQL:

    Once the download is complete, follow these steps to install MySQL:

    a. Double-click the downloaded installer (or extract the ZIP archive) to launch the MySQL Installer.

    b. Select "Custom" installation to choose the specific components you want to install.

    c. In the list of available products, select the following:

    1. MySQL Server: The actual MySQL database server responsible for data storage and retrieval.
    2. MySQL Workbench: A graphical tool for managing and interacting with MySQL databases.
    3. MySQL for Visual Studio: A plugin for Microsoft Visual Studio to enable MySQL integration.
    4. MySQL Shell: A command-line tool with advanced features for database management.
    5. MySQL Router: A utility for distributing client connections across multiple MySQL instances.
    6. Connector/J: The JDBC driver for Java applications to connect to MySQL databases.

    d. Click the "Next" button to proceed with the installation.

    e. Follow the on-screen instructions, including choosing installation paths, configuring passwords, and selecting start-up options.

    f. Once the installation is complete, you will have a fully functional MySQL database system along with the selected tools and connectors.

  3. Configuring MySQL:

After installing MySQL Server 8.1 or higher, you may need to configure it based on your specific requirements. The configuration process allows you to customize various settings, such as the server port, authentication methods, character set, and more. Starting from MySQL 8.1, MySQL Configurator is bundled with the server to streamline the configuration process.

Note: If you don't know what you are doing just keep clicking "Next" until you get a page to enter the password. give a strong password there and keep clicking "Next" until it is finished

Here's a detailed guide on how to configure MySQL using MySQL Configurator:

  1. Launch MySQL Configurator:

    After completing the installation of MySQL, you can launch MySQL Configurator using one of the following methods:

    • Windows: Go to the Start menu, find "MySQL", and select "MySQL Server 8.1" or the corresponding version. Click on "MySQL Configurator."
    • Linux/macOS: Open a terminal and type mysqlc or mysqlcsh (depending on your preferred shell) and hit Enter.
  2. Select Configuration Type:

    Upon launching MySQL Configurator, you will be prompted to choose a configuration type. There are two options:

    • Standalone Server: Select this option if you want to configure a single MySQL server.
    • InnoDB Cluster: Choose this option if you want to set up a cluster with multiple MySQL instances in an InnoDB cluster configuration.

    Select the appropriate configuration type based on your needs and click "Next."

  3. Configure Server Settings:

    The next step allows you to configure various server settings. These include:

    • Port Number: Specify the port number that MySQL will listen on for incoming client connections. The default is 3306.
    • Authentication Method: Choose the authentication method for MySQL users. You can select either "Use Legacy Authentication Method (Retain MySQL 5.x Compatibility)" or "Use Strong Password Encryption (Recommmended)" based on your security requirements. The latter is recommended for enhanced security.
    • Character Set: Set the default character set for the server. The default is utf8mb4, which supports a wide range of characters.

    Configure these settings according to your preferences, and click "Next."

  4. Set Root Password:

    In this step, you will be prompted to set the root password for the MySQL server. It is crucial to choose a strong password for the root user, as it provides administrative access to the database server. Enter and confirm your desired root password, and click "Next."

  5. Review Configuration Summary:

    MySQL Configurator will display a summary of the configuration settings you have chosen. Review the summary carefully to ensure that all the settings are as intended.

  6. Apply Configuration:

    Once you are satisfied with the configuration summary, click the "Apply Configuration" button to apply the settings. MySQL Configurator will execute the necessary steps to configure the MySQL server based on your selections.

  7. Start MySQL Server:

    After the configuration process is complete, MySQL Configurator will automatically start the MySQL server with the new settings. You can verify that the server is running by checking the status message in the MySQL Configurator window.

  8. Manage MySQL Server:

    After successful configuration, you can manage the MySQL server using various tools, such as MySQL Workbench or the MySQL Shell. MySQL Workbench provides a graphical interface for database management, while the MySQL Shell offers a powerful command-line interface with advanced features.

  9. Connecting to MySQL Server:

    To connect to the configured MySQL server, use the appropriate client application or programming language. For instance, you can use MySQL Workbench, the MySQL Shell, or JDBC (for Java applications) to establish connections and interact with the MySQL database.

Using JDBC and MySQL in Java

JDBC (Java Database Connectivity) is a powerful API that enables Java applications to interact with relational databases, such as MySQL. In this comprehensive guide, we will walk through three different scenarios to use JDBC and MySQL in Java:

  1. Creating a Java project in Visual Studio Code (VSCode) and setting up the JDBC connector.
  2. Creating a Java project in Eclipse, IntelliJ, or NetBeans and configuring the JDBC connector.
  3. Writing and running code using just Notepad and managing the connector in the system's path.

Let's dive into each scenario:

Part 1: Using JDBC and MySQL in Visual Studio Code (VSCode):

  1. Create a Java Project:

    • Open Visual Studio Code and create a new folder for your Java project.
    • Inside the folder, create a new file named MyApp.java. This will be your main Java file.
  2. Add the JDBC Connector:

    • Download the latest MySQL JDBC connector (e.g., mysql-connector-java-x.x.x.jar) from the MySQL website (https://dev.mysql.com/downloads/connector/j/).
    • Move the downloaded JAR file to a location on your system (e.g., C:\mysql-connector-java-x.x.x.jar).
  3. Reference the Connector in VSCode:

    • Open the terminal in VSCode (View > Terminal) and navigate to your project folder.
    • Run the following command to compile the Java code and reference the MySQL JDBC connector:
      javac -cp .;C:\mysql-connector-java-x.x.x.jar MyApp.java
      
    • If you encounter any issues with the classpath, adjust the path to the connector JAR accordingly.
    • You can optionally create a java project then add reference library and add the mysql-connector-java-x.x.x.jar jar file. if you are having problems follow this video.
  4. Sample Code:

    import java.sql.*;
    
    public class MyApp {
        public static void main(String[] args) {
            try {
                // Load the JDBC driver
                Class.forName("com.mysql.cj.jdbc.Driver");
    
                // Establish the connection
                String dbUrl = "jdbc:mysql://localhost:3306/mydatabase";
                String username = "your_username";
                String password = "your_password";
                Connection conn = DriverManager.getConnection(dbUrl, username, password);
    
                // Create a statement
                Statement stmt = conn.createStatement();
    
                // Execute a query
                String sqlQuery = "CREATE TABLE IF NOT EXISTS users (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50), age INT)";
                stmt.execute(sqlQuery);
    
                // Close resources
                stmt.close();
                conn.close();
    
                System.out.println("Database and table created successfully.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
  5. Check Database Creation in Terminal:

    • To check if the database was created, open the MySQL command-line client in the terminal and log in using your credentials:
      mysql -u your_username -p
      
    • Enter your password when prompted.
    • Use the following command to view the list of databases:
      SHOW DATABASES;
      
    • You should see your database (mydatabase in the sample code) in the list.

Part 2: Using JDBC and MySQL in Eclipse, IntelliJ, or NetBeans:

  1. Create a Java Project:

    • Open your preferred IDE (Eclipse, IntelliJ, or NetBeans) and create a new Java project.
    • Inside the project, create a new Java class named MyApp.
  2. Add the JDBC Connector:

    • Download the latest MySQL JDBC connector (e.g., mysql-connector-java-x.x.x.jar) from the MySQL website (https://dev.mysql.com/downloads/connector/j/).
    • Copy the downloaded JAR file to a location on your system (e.g., C:\mysql-connector-java-x.x.x.jar).
  3. Reference the Connector in the IDE:

    • In Eclipse:
      • Right-click on the project in the Project Explorer.
      • Select Build Path > Configure Build Path.
      • Click on the Libraries tab.
      • Click "Add External JARs..." and navigate to the location of the JDBC connector JAR. Click "Apply and Close."
    • In IntelliJ:
      • Right-click on the project in the Project Explorer.
      • Select "Open Module Settings."
      • Click on "Libraries" in the left pane.
      • Click the "+" icon and add the JDBC connector JAR. Click "OK."
    • In NetBeans:
      • Right-click on the project in the Projects view.
      • Select Properties > Libraries > Compile tab.
      • Click "Add JAR/Folder" and navigate to the location of the JDBC connector JAR. Click "OK."
  4. Sample Code: (Use the same code as shown in Part 1 for the MyApp class.)

  5. Check Database Creation in Terminal: (Follow the same steps as shown in Part 1 to check if the database was created.)

Part 3: Using JDBC and MySQL with Notepad:

  1. Write and Save the Java Code:

    • Open Notepad and write the Java code (the same code as shown in Part 1) in a new file named MyApp.java.
    • Save the file in a folder named MyProject.
  2. Add the JDBC Connector to the System Path:

    • Download the latest MySQL JDBC connector (e.g., mysql-connector-java-x.x.x.jar) from the MySQL website (https://dev.mysql.com/downloads/connector/j/).
    • Move the downloaded JAR file to a location on your system (e.g., C:\mysql-connector-java-x.x.x.jar).
  3. Compile and Run the Code:

    • Open the Command Prompt (cmd) and navigate to the MyProject folder.
    • Compile the Java code and reference the MySQL JDBC connector by running the following command:
      javac -cp .;C:\mysql-connector-java-x.x.x.jar MyApp.java
      
    • If the compilation is successful, run the code with the following command:
      java -cp .;C:\mysql-connector-java-x.x.x.jar MyApp
      
  4. Check Database Creation in Terminal: (Follow the same steps as shown in Part 1 to check if the database was created.)

Complete Demo Project with JDBC and MySQL:

In this comprehensive demo project, we'll create a Java application that utilizes JDBC to interact with a MySQL database. The project will follow a proper architecture with classes for ConfigLoader, DBHelper, Controller, Model, and View. The user interface will be implemented using Java Swing, and the project structure adheres to best practices for easy maintenance and scalability.

Project Structure:

JDBCMySQLDemo
│   ├── src
│   │   ├── main
│   │   │   ├── java
│   │   │   │   ├── com
│   │   │   │   │   ├── demo
│   │   │   │   │   │   ├── controller
│   │   │   │   │   │   │   └── UserController.java
│   │   │   │   │   │   ├── model
│   │   │   │   │   │   │   └── User.java
│   │   │   │   │   │   ├── util
│   │   │   │   │   │   │   ├── ConfigLoader.java
│   │   │   │   │   │   │   └── DBHelper.java
│   │   │   │   │   │   └── view
│   │   │   │   │   │       └── UserView.java
│   │   │   │   │   ├── main.java
│   │   │   └── resources
│   │   │       ├── db.properties
│   │   │       └── images
│   │   │           └── logo.png

ConfigLoader.java:

package com.demo.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigLoader {
    private static final String PROP_FILE = "db.properties";

    public Properties loadProperties() {
        Properties properties = new Properties();
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(PROP_FILE)) {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }
}

DBHelper.java:

package com.demo.util;

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

public class DBHelper {
    private final String dbUrl;
    private final String username;
    private final String password;

    public DBHelper(Properties properties) {
        dbUrl = properties.getProperty("db.url");
        username = properties.getProperty("db.username");
        password = properties.getProperty("db.password");
    }

    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(dbUrl, username, password);
    }
}

User.java (Model):

package com.demo.model;

public class User {
    private int id;
    private String name;
    private int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

UserController.java (Controller):

package com.demo.controller;

import com.demo.model.User;
import com.demo.util.DBHelper;

import java.sql.*;

public class UserController {
    private final DBHelper dbHelper;

    public UserController(DBHelper dbHelper) {
        this.dbHelper = dbHelper;
    }

    public void createUser(User user) {
        String query = "INSERT INTO users (name, age) VALUES (?, ?)";

        try (Connection conn = dbHelper.getConnection();
             PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {

            statement.setString(1, user.getName());
            statement.setInt(2, user.getAge());

            int affectedRows = statement.executeUpdate();

            if (affectedRows == 0) {
                throw new SQLException("Creating user failed, no rows affected.");
            }

            try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    user.setId(generatedKeys.getInt(1));
                } else {
                    throw new SQLException("Creating user failed, no ID obtained.");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public User getUserById(int userId) {
        String query = "SELECT * FROM users WHERE id = ?";

        try (Connection conn = dbHelper.getConnection();
             PreparedStatement statement = conn.prepareStatement(query)) {

            statement.setInt(1, userId);
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    User user = new User();
                    user.setId(resultSet.getInt("id"));
                    user.setName(resultSet.getString("name"));
                    user.setAge(resultSet.getInt("age"));
                    return user;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}

UserView.java (View):

package com.demo.view;

import com.demo.model.User;

import javax.swing.*;
import java.awt.*;

public class UserView {
    public void displayUserDetails(User user) {
        JFrame frame = new JFrame("User Details");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setLocationRelativeTo(null);

        JPanel panel = new JPanel(new GridLayout(2, 1));
        frame.add(panel);

        JLabel nameLabel = new JLabel("Name: " + user.getName());
        JLabel ageLabel = new JLabel("Age: " + user.getAge());

        panel.add(nameLabel);
        panel.add(ageLabel);

        // Add logo image to the frame
        ImageIcon logoIcon = new ImageIcon(getClass().getClassLoader().getResource("images/logo.png"));
        JLabel logoLabel = new JLabel(logoIcon);
        frame.add(logoLabel, BorderLayout.WEST);

        frame.setVisible(true);
    }
}

Main.java:

package com.demo;

import com.demo.controller.UserController;
import com.demo.model.User;
import com.demo.util.ConfigLoader;
import com.demo.util.DBHelper;
import com.demo.view.UserView;

import java.util.Properties;

public class Main {
    public static void main(String[] args) {
        // Load configuration properties
        ConfigLoader configLoader = new ConfigLoader();
        Properties properties = configLoader.loadProperties();

        // Create DBHelper and UserController
        DBHelper dbHelper = new DBHelper(properties);
        UserController userController = new UserController(dbHelper);

        // Sample usage
        User newUser = new User("John Doe", 30);
        userController.createUser(newUser);

        // Retrieve the user from the database by ID
        int userId = newUser.getId();
        User retrievedUser = userController.getUserById(userId);

        // Display user details using the view
        UserView userView = new UserView();
        userView.displayUserDetails(retrievedUser);
    }
}

db.properties:

db.url=jdbc:mysql://localhost:3306/sample_db
db.username=username
db.password=password

Note: Replace sample_db, username, and password with your MySQL database name, username, and password, respectively.

This demo project showcases a complete Java application with proper architecture, including ConfigLoader for loading properties, DBHelper for handling database connections, UserController for CRUD operations on the User model, and UserView for displaying user details using Java Swing. The main class demonstrates how these components are used together to create a new user, retrieve their details from the database, and display the information using the Java Swing GUI along with the application logo stored in the images folder within the resources directory. The project structure follows best practices and separates concerns for easy maintenance and scalability. The User model has constructors, getters, setters, and a toString method for better handling of user data. The UserController has methods for creating a user and retrieving a user by ID from the database.

Conclusion:

JDBC (Java Database Connectivity) plays a crucial role in enabling Java applications to interact with relational databases like MySQL. It simplifies the process of connecting to databases, executing SQL queries, and processing results. The automated JDBC driver loading in newer versions eliminates the need for manual driver registration, streamlining database connectivity. Configuring MySQL Server using MySQL Configurator ensures a user-friendly setup and customization. Choosing between MySQL 8.0.34 and MySQL 8.1.0 depends on factors like stability and features. Finally, our comprehensive guide demonstrates how to set up JDBC with MySQL in various environments, making it easier for developers to build robust and data-driven Java applications.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment