Saturday, March 14, 2009

Using JDBC with MySQL

To write Java programs that use a MySQL database you need to do four things:
  1. Install MySQL Server (there will come an article on this in the future)
  2. Install JDK and Eclipse
  3. Install the MySQL Connector/J
  4. Write a test program
In this article details steps 3 and 4.


Install the MySQL Connector/J

The package java.sql in the JDK provides interfaces for working with the database. The implementation of this interfaces is particular to each Database Mangement System (DBMS) (i.e. Oracle, MsSql, MySQL, etc.) and is provided through drivers. In this way your code is independent of DBMS. When you decide to change the DBMS you just need to change the driver, while your code stays the same.

MySQL Connector/J is a native Java driver that converts JDBC (Java Database Connectivity) calls into the network protocol used by the MySQL database.

Installing MySQL Connector/J:

  • download MySQL Connector/J 5.0 (or other version)
  • unpack the archive and copy mysql-connector-java-5.0.8-bin.jar in jre1.6.0_02\lib\ext directory. (jre1.6.0_02 can have different sufix depending on the JDK version you have installed; you can find it in the directory where you installed the JDK.)
This is all what it takes to install the driver for MySQL. Information was taken from the driver archive: \docs\README.txt (1.2.2. Installing the Driver and Configuring the CLASSPATH).


Write a test program

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
* Test connection to a MySQL database installed on local machine.
*
* @author Mihai Ionut Rus
*/
public class TestMySQL {

public static void main(String[] args) {
try {
Statement stmt;

// Register the JDBC driver for MySQL.
Class.forName("com.mysql.jdbc.Driver");

String url = "jdbc:mysql://localhost:3306/mysql";

/*
* Get a connection to the database for a user named root with a blank
* password. If have a password for root, you must provide it.
*/
Connection con = DriverManager.getConnection(url, "root", "");

System.out.println("URL: " + url);
System.out.println("Connection: " + con);

//Create a test database
stmt = con.createStatement();
stmt.executeUpdate("CREATE DATABASE JunkDB");

con.close();
} catch (Exception e) {
e.printStackTrace();
}
}

}