Java JDBC How to - Connect to MySQL Database








Question

We would like to know how to connect to MySQL Database.

Answer

import java.sql.Connection;
import java.sql.DriverManager;
/*w  w  w  . j  a  v a 2s  .c om*/
public class Main {

  public static void main(String[] argv) throws Exception {

    Class.forName("com.mysql.jdbc.Driver");

    System.out.println("MySQL JDBC Driver Registered!");
    Connection connection = null;

    connection = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/dbName", "root", "password");

    if (connection != null) {
      System.out.println("database now!");
    } else {
      System.out.println("Failed to make connection!");
    }
  }
}