Scroll to top

How to connect to mysql database in java

Here we will learn to connect to MYSQL DB via Java.

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

 * Here we will learn to connect to Oracle DB using JDBC Driver.
public class ConnectMySQLDB {

	public static void main(String[] args) {

		Scanner scanner = new Scanner(;
				.println("Please provide below details to connect MySQL Database");
		System.out.println("Enter Database");
		String dbName =;
		System.out.println("Enter UserName");
		String userName =;
		System.out.println("Enter Password");
		String password =;

		try {


		} catch (ClassNotFoundException e) {

		Connection connection = null;

		try {
			connection = DriverManager
					.getConnection("jdbc:mysql://localhost:3306/" + dbName,
							userName, password);

		} catch (SQLException e) {

		if (connection != null) {
			System.out.println("nSuccessfullly connected to MySQL DB");
		} else {
			System.out.println("nFailed to connect to MySQL DB");




JARs Required :

mysql-connector-java-5.1.22-bin.jar(Download Here)

Tools Used :

Eclipse Indigo

Java Version

JDK 1.6

Author avatar

1 comment

  1. marcos

    this is just connect and disconnect. how about do select?

Post a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.