May 202016

ADM

How to connect to MySQL with JDBC driver

  • May 20 2016
  • ADM

 

 

How to connect to MySQL with JDBC driver - jdbc

 

Java Database Connectivity (JDBC) is an application programming interface (API) for the Java programming language, which defines how a client may access a database. The JDBC classes are contained in the Java package java.sql and javax.sql and it is delivered as part of the Java Platform, Standard Edition (Java SE).

Introduction

Having the API defined for each database engine will need an implementation of the JDBC API. As we are going to use MySQL, before starting we need to get the MySQL JDBC driver from MySQL JDBC Driver Download.

There are two simple steps for this:

  • load the JDBC driver;
  • get the connection using DriverManager class.

Pre-requirements

  • MySQL install on local PC.
  • MySQL up and running on port 3306.
  • Database 'admfactory.com' already created.

Note: Adjust connect function if some of these pre-requirements are different.

If you need help preparing your development machine and if you are using Windows as operating system, this might help.

Example

package com.admfactory.db;

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

public class JDBCConnect {

    private static Connection connect() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/admfactory.com", "root", "");
        } catch (Exception e) {
            System.out.println("Failed to connect to DB.");
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        try {
            /** Get the connection. */
            Connection connection = connect();

            /** Check the connection. */
            if (connection != null) {
                System.out.println("Connection successful!");
            } else {
                System.out.println("Failed!");
            }

            /** Close the connection. */
            connection.close();
        } catch (Exception e) {
            System.out.println("Something went wrong.");
        }

    }
}

Output

Testing MySQL database connection.
Connection successful!

References