Pages Navigation Menu

Coding is much easier than you think

Connect to MySQL DB via JDBC driver

 
Here’s an example to show you how to connect to MySQL database via a JDBC driver.
 
1. Download MySQL JDBC Driver
 
Get MySQL JDBC driver here –MySQL JDBC Driver

 2. Java JDBC connection example
 
Code snippets to use a JDBC driver to connect a MySQL database.
 
** UPDATE: Complete JDBC tutorial now available here.
 

Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username",
         "password");
conn.close();

 
See a complete example below:

File: MySqlJDBC.java
 

package com.simplecode.jdbc;

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

public class MySqlJDBC {

private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/simplecodedb";
private static final String DB_USER = "username";
private static final String DB_PASSWORD = "password";

public static void main(String[] argc) {

	System.out.println("***** MySQL JDBC Connection Testing *****");

	try
	{
		Class.forName(DB_DRIVER);
	}
	catch (ClassNotFoundException e)
	{
		System.err.println("Exception : Add MySQL JDBC Driver in your classpath ");
                System.err.println(e.getMessage());
		return;
	}

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

	try
	{
	connection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
	}
	catch (SQLException e)
	{
		System.err.println("Connection Failed! Check console");
                System.err.println(e.getMessage());
		return;
	}

	if (connection == null) {
		System.out.println("Connection Failed!");
	}
	else
	{
		System.out.println("Connection established!");
	}
}
}