How to set up Connector/J in Eclipse

Connector/J is a “Type IV JDBC driver for MySQL.”

Assumptions

You have downloaded & installed MySQL 5.1, Connector/J for 5.1 (the JDBC driver for MySQL) from mysql.com, Tomcat 5.5 or 6, Eclipse 3.4 for Java EE. I’m assuming this is a Dynamic Web Project in Eclipse with Tomcat 6 as the Target Runtime. I did this successfully on OS X 10.5 (Leopard) & on Windows XP.

The Steps:

  1. Select your project folder in Eclipse’s Project Explorer (just click on it so it’s highlighted).
  2. Open project properties. There’re several ways to do this. For example, you can go to Project > Properties in Eclipse’s top menu.
  3. Click on Java Build Path. Click “Add External Jars.” Navigate to where you unzipped Connector/J on your hard drive. Choose the .jar file (in my case mysql-connector-java-5.1.7-bin.jar) & click Open. It’ll now show up under JARs and class folders in the build path.
  4. Click on Java EE Module dependencies in the menu on the left.
  5. Check the checkbox next to the Connector/J path under JAR/Module. Hit Apply and OK.
    Run a skeleton test Servlet to see if it works:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestJDBC extends HttpServlet {

    public void init(){
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            System.out.println("JDBC driver loaded");
        } catch (ClassNotFoundException e) {
            System.out.println(e.toString());
        } //Eclipse may auto-force some extra catch blocks here
     }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("Check the Console tab in" +
		" Eclipse... it should say \"JDBC driver loaded\"");
    }

}