Points To Remember 
  • Download Mysql Java Connector by clicking on the link.
  • Put the above downloaded jar file in the lib folder of your project.
Code : Mysql JDBC connection in Java
import java.sql.Connection;
import java.sql.DriverManager;

public class JavaMysqlConnection {

private String host = "localhost:3306"; // For running on localhost
private String db = "databaseName";
private String userName = "userName";
private String password = "password";

public Connection getConnection() {
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://"+ host +"/"+db,userName, password);
return conn;
}catch(Exception e){
return null;

public class Test{

public static void main(String[] argv) {
Connection conn = new JavaMysqlConnection().getConnection();
if(conn == null)
System.out.println("Connection was not established");
System.out.println("Connection is successfully established");

This is a very generic code that you can use in both your standalone projects and web based projects. Whenever you need to get a connection to database, you just need to create an object of class JavaMysqlConnection and call its getConnection() method.