To connect a Java application with MySQL, we need a driver as interface between Java and MySQL. Driver can be downloaded from the official MySQL website.

[ Download MySQL Connector ]

Extract downloaded file (file type: *.jar). Copy that file to directory [jre installation]/lib/ext/. Ok, your Java application is ready to connect with MySQL.

Testing
Code below is used to connect between Java and MySQL.
/*
* DBConnection.java
*
* Created on 29 September 2007, 11:41
*
*/

import java.sql.*;

/**
*
* @author Dani Gunawan
*/
public class DBConnection {

/** Creates a new instance of DBConnection */
public DBConnection() {
}

public Connection connect() {
Connection conn = null;

try
{
String userName = “root”;
String password = “”;
String url = “jdbc:mysql://blog.danigunawan.com/test”;
Class.forName (“com.mysql.jdbc.Driver”).newInstance ();
conn = DriverManager.getConnection (url, userName, password);
} catch (Exception e) {
e.printStackTrace();
conn = null;
} finally {
if (conn != null)
{
try
{
conn.close ();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}

return conn;
}
}

Code below is used to test the database connection.

/**
* TesConnection.java
*/
import java.sql.*;

public class TesConnection {

public static void main(String args[]) {

Connection dbcon = new DBConnection().connect();

if (dbcon != null) {
System.out.println(“Database connection is successfully created”);
} else {
System.out.println(“Database connection isn’t successfully created”);
}
}

}

How to Use Them?
Put those two source in the same directory. Compile DBConnection.java and TesConnection.java respectively.

javac DBConnection.java

javac TesConnection.java

If you want to compile all of them, use wildcard asterisk (*).

javac *.java

Run TesConnection:

java TesConnection

If the result:

Database connection is successfully created

Then your database is has been connected. But if:

Database connection isn’t successfully created

means your Java application isn’t connected yet with the database.
Possibility:
- MySQL isn’t installed yet
- Database hasn’t been created yet (or maybe wrong database name)
- Wrong database user or password

Both source can be downloaded from link below:

[ Download example file ]

P.S.:
Code had been tested in Windows XP SP 2 Operating System, never been done in other operating systems.

Related posts:

  1. How To Install Java in Linux Ubuntu
  2. Creating Database in MySQL
  3. After Oracle Bought Sun

Tags: ,

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>