To connect MySQL using JDBC mysql-connector-java-{version}-bin.jar should be available in your class path. You could Google and download this jar and include in your class path.

Connect MySQL using JDBC sample java program:

package com.javahonk;

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

public class GetMySQLConnection {

	public static void main(String[] args) {

	Connection connection = null;

	try {
	// Register JDBC Driver
	Class.forName("com.mysql.jdbc.Driver");
	// Open connection
	connection = DriverManager.getConnection(
			"jdbc:mysql://localhost:3306/javahonk",
			"root", "admin");
	if (null != connection) {
		System.out.println("Sucessfully "
				+ "connected to MySQL database!!!");
	} else {
		System.out.println("Connection "
				+ "to MySQL database failed!!!");
	}

	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	}

}

 

Output:

Connect MySQL using JDBC

That’s it for Connect MySQL using JDBC

Leave a Reply

Your email address will not be published. Required fields are marked *