Java and MySQL Introduction

MySQL is a database that can be used in conjunction with Java to create desktop, web and console based application. It can be used to store data, as well as configuration information. Java, together with SQL, can be used to query the data stored within a MySQL database, as well as insert, update and delete the data. In order for this to be possible, the MySQL JDBC Driver needs to be used.

Connecting to a MySQL Database

In order to access data within a MySQL database with Java, a connection to the database must first be established. Below is an example of how this can be achieved.

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

public class DemoMySQL {

    public static void main(String[] args) {

        // Database and connection variables.
        String database = "jdbc:mysql://localhost:3306/Demo?useSSL=false";
        String username = "DemoUN";
        String password = "DemoPW";
        Connection connect = null;

        try {

            // Connect to database.
            connect = DriverManager.getConnection(database, username, password);

            // Message confirming successful database connection.
            System.out.println("Database connection successful.");

        } catch (SQLException e) {

            // Message confirming unsuccessful database connection.
            System.out.println("Database connection unsuccessful.");

            // Stop program execution.
            System.exit(0);

        }

    }

}

In this example, a ‘try-catch’ block is used to catch any exceptions that may arise in connecting to the database, which, in this case, is running on the same machine, or ‘localhost’, as the program. A ‘try-catch’ block can be used to handle any exceptions in a user friendly manner. The ‘System.exit(0)’ statement, after the confirmation of an unsuccessful database connection, stops execution of the program completely, so no further statements are executed.

It should be noted that it isn’t necessary to have the database information in separate variables before using it in the database connection. It much depends on personal preference and whether the variables are going to be re-used elsewhere in the program. The database connection variable can be re-written as follows.

// Connect to database.
connect = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/Demo?useSSL=false",
        "DemoUN", "DemoPW");