How to connect to MySQL with JDBC driver

  • 20 May 2016
  • ADM


How to connect to MySQL with JDBC driver - images/logos/jdbc.jpg


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).


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.


  • MySQL install on local PC.
  • MySQL up and running on port 3306.
  • Database '' 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.


package com.admfactory.db;

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

public class JDBCConnect {

    private static Connection connect() {
        try {
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "");
        } catch (Exception e) {
            System.out.println("Failed to connect to DB.");
            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 {

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



Testing MySQL database connection.
Connection successful!