Connecting to MySQL using Java

This tutorial will guide you throught the most fundamental steps in connecting to MySQL using Java. The very first thing you should start with is getting the JDBC driver for MySQL.

  1. Go to the MySQL website and download the Java JDBC driver. Link Download the “JDBC Driver for MySQL (Connector/J)”
  2. Create a new Project in Eclipse or Netbeans or anyother IDE that you might be using for Java.
  3. Add the JDBC driver to the library path in your project properties window
  4. Create or use an existing mysql database, with dummie data.
  5. Download this mysql class. MySQLService.java
  6. Create a simple class that initiate the MySQLService class and do a query.
  7. Here is a guide of how to handle the returning value ResultSet of the doQuery

  8. mysql.connect();
    ResultSet result = mysql.doQuery("SELECT * FROM reports_categories");

    while(result.next())
    {
    System.out.println(result.getObject("category_id").toString()+","
    +result.getObject("category_name").toString());
    }
    result.close();
    mysql.close();

  9. The attached jva file MySQLService.java, the function doQuery only accepts SQL SELECT statements for now. I’ll update this article and the java file with other functions that allows for insertion and update of rows.

Leave a Comment