The Way Of Life: How to Connect Java to MySQL

Tuesday, June 28, 2011

How to Connect Java to MySQL

After we learn how to connecting Java Program to Microsoft SQL Server, now we learn to connecting our java program to MySQL.

So we must prepare tools for that, and the tools is:

1. NetBeans IDE 7.0, you can download here.
2. MySQL 5.0 , and you can download here.
3. JDBC Driver for MySQL, you can download on this site. Add this driver to our Java Project library that we will make it.

First, we must create project Java on NetBeans IDE, for the example ConnectMySQL.
And then create packages by right click on Source Packages and choose New -> Java Packages and create name on that packages for the example same with the Project Name Connect MySQL.

After that, create one class by right click on our new packages , and choose New -> Java Class and create our New Java Class with and type or copy paste this code on our new Java Class.

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

class MySQLConnection{
Connection Connect;
public Connection ConnectDB(){
String url = "jdbc:mysql://localhost/test";

Connect = DriverManager.getConnection(url, "root", "root");

}catch(ClassNotFoundException e){
System.out.println("Driver Load Failed!");
}catch(SQLException e){
System.out.println("Connection Failed!");
return Connect;

public static void main(String[] abc){
Connection Con = new MySQLConnection().ConnectDB();
if(Con != null){
System.out.println("Connection Succesfull!");
System.out.println("Connection Failed!");

If you have finished, then we must create New Java Form by right click on MySQLServer packages and then choose New -> JFrame Form. And create one button and name on it with "Test Connection MySQL". And then copy paste this code to our new button.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = new MySQLConnecTautantion().ConnectDB();
if(con != null){
JOptionPane.showMessageDialog(null, "Connection Succesfull!");
JOptionPane.showMessageDialog(null, "Connection Failed!");
}catch(Exception e){


and do the same thing like our Java to SQL Server project.

Labels: , , ,


Post a Comment

<< Home