MacLochlainns Weblog

Michael McLaughlin's Technical Blog

Site Admin

Eclipse, Java, MySQL

without comments

While I previously blogged about installing Netbeans 8, some of my students would prefer to use the Eclipse IDE. This post shows how to install and configure Eclipse IDE, include the mysql-connector-java.jar, and write Java to access the MySQL.

You can download Eclipse IDE and then open it in Fedora’s Archive Manager. You can use the Archive Manager to Extract the Eclipse IDE to a directory of your choice. I opted to extract it into my student user’s home directory, which is /home/student.

After extracting the Eclipse IDE, you can check the contents of the eclipse directory with the following command:

ls -al eclipse

You should see the following:

drwxrwxr-x.  8 student student   4096 May  8 22:16 .
drwx------. 33 student student   4096 May  8 21:57 ..
-rw-rw-r--.  1 student student 119194 Mar 20 07:10 artifacts.xml
drwxrwxr-x. 11 student student   4096 May  8 22:16 configuration
drwxrwxr-x.  2 student student   4096 Mar 20 07:10 dropins
-rwxr-xr-x.  1 student student  78782 Mar 20 07:08 eclipse
-rw-rw-r--.  1 student student    315 Mar 20 07:10 eclipse.ini
-rw-rw-r--.  1 student student     60 Mar 17 15:11 .eclipseproduct
drwxrwxr-x. 41 student student   4096 Mar 20 07:10 features
-rwxr-xr-x.  1 student student 140566 Mar 20 07:08 icon.xpm
drwxrwxr-x.  4 student student   4096 Mar 20 07:09 p2
drwxrwxr-x. 12 student student  40960 Mar 20 07:10 plugins
drwxrwxr-x.  2 student student   4096 Mar 20 07:10 readme

You can launch the Eclipse IDE with the following command-line from the eclipse directory:

./eclipse &

While you can run this from the /home/student/eclipse directory, it’s best to create an alias for the Eclipse IDE in the student user’s .bashrc file:

# Set alias for Eclipse IDE tool.
alias eclipse="/home/student/eclipse/eclipse"

The next time you start the student user account, you can launch the Eclipse IDE by entering eclipse in the search box opened by clicking on the Activities menu.

The following steps take you through installing Eclipse on Fedora Linux, which is more or less the same as any Linux distribution. It’s very similar on Windows platforms too.

Eclipse Installation

EclipseInstall_01

  1. Navigate to eclipse.org/downloads web page to download the current version of the Eclipse software. Click the Linux 32 Bit or Linux 64 Bit link, as required for your operating system.

  1. Click the Green Arrow to download the Eclipse software.

  1. The next dialog gives you an option to open or save the software. Click the Open with radio button to open the archive file.

  1. This the Linux Archive Manager. Click the Extract button from the menu tab to open the archive file.

  1. This extract button on file chooser dialog to install Eclipse into the /home/student/eclipse directory. Click the Extract button to let the Archive Manager create a copy of those files.

  1. The Archive Manager presents a completion dialog. Click the Close button to close the Archive Manager.

After installing the Eclipse software, you can configure Eclipse. There are sixteen steps to setup the Eclipse product. You can launch the product with the

Eclipse Setup

You need to launch the Eclipse application to perform the following steps. The syntax is the following when you did create the alias mentioned earlier in the blog post:

eclipse &

The following steps cover setting up your workspace, project, and adding the MySQL JDBC Java archive.

  1. The branding dialog may display for 30 or more seconds before the Eclipse software application launches.

  1. The Workspace Launcher opens first on a new installation. You need to designate a starting folder. I’m using /home/student/workspace as my Workspace. Click the OK button when you enter a confirmed workspace.

  1. After setting the Workspace Launcher, you open to the Eclipse Welcome page. Click second of the two icons on the left to open a working Eclipse environment. Alternatively, you can connect to Tutorials on the same page.

  1. From the developer view, click on the File menu option, the New option on the list, and the Java Project option on the floating menu. Eclipse will now create a new Java project.

  1. The New Java Project dialog lets you enter a project name and it also gives you the ability to set some basic configuration details. As a rule, you simply enter the Project Name and accept the defaults before clicking the Finish button.

  1. After creating the new Java project, Eclipse returns you to the Welcome page. Click second of the two icons on the left to open a working Eclipse environment.

  1. Now you should see the working environment. Sometimes it takes the full screen but initially it doesn’t. Navigate to the lower right hand side, and expand the window to full size.

  1. Now you should see the full screen view of the Eclipse working environment.

  1. Now you create a new Java class by navigating to the File menu options, then the New menu option, and finally choosing the Class floating menu.

  1. The New Java Class dialog requires you to provide some information about the Java object you’re creating. The most important thing is the Java class name.

  1. The only difference in this copy of the New Java Class dialog is that I’ve entered HelloWorld as the Java Class’s name. Click the Finish button when you’re done.

  1. Eclipse should show you the following HelloWorld.java file. It’s missing a main() method. Add a static main() method to the HelloWorld.java class source file.

  1. This form shows the changes to the HelloWorld.java file. Specifically, it adds the It’s missing a main() method. Add a static main() method to the HelloWorld.java class source file.

  1. You can click the green arrow from the tool panel or you can click the Run menu option and Run submenu choice to test your program.
    1
    2
    3
    4
    
    // Class definition.
    public class HelloWorld {
      public static void main(String args[]) {
        System.out.println("Hello World."); }}

  1. The Save and Launch dialog tells you that you’re ready to test creating a copy of the Java class file. Click the OK button to continue.

  1. The results from your program are written to the Console portion of the Eclipse IDE. This concludes the setup of a workspace, project, and deployment of actual Java classes.
    Hello World.

Add MySQL JDBC Library

The following instructions add the MySQL Library and demonstrate how to write Java programs that connect to the MySQL database. They also use the mysql project.

EclipseMySQLLib_01

  1. Navigate to the Project menu and choose the Properties menu option.

EclipseMySQLLib_02

  1. The Properties menu option opens the Properties for the mysql project on the Order and Export tab. Click the Libraries tab to add an external library.

EclipseMySQLLib_03

  1. In the Libraries tab click the Add Library… button on the right to add an external library.

EclipseMySQLLib_04

  1. In the JAR Selection dialog, click on Computer in the Places list, then click on usr, click on share, and click on java. The Name list should now include mysql-connector-java.jar file, and you should click on it before clicking on the OK button.

EclipseMySQLLib_05

  1. You create new Java class file by clicking on the File menu. Then, you choose the New menu option and the Class menu option from the floating menu.

EclipseMySQLLib_06

  1. Enter MysqlConnector as the name of the new Java class file and click the Finish button to continue.

EclipseMySQLLib_07

  1. Eclipse generates the shell of the MysqlConnector class as shown in the illustration to the left.

EclipseMySQLLib_08

  1. You should replace the MysqlConnector class shell with the code below. Then, click the green arrow or the Run menu and Run menu option to compile and run the new MysqlConnector Java class file.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
     
    public class MysqlConnector extends Object {
      public static void main(String[] args) {
        try {
          /* The newInstance() call is a work around for some
             broken Java implementations. */
          Class.forName("com.mysql.jdbc.Driver").newInstance();
     
          /* Verify the Java class path. */
          System.out.println("====================");
          System.out.println("CLASSPATH [" + System.getProperty("java.class.path") + "]");
          System.out.println("====================");
     
        } catch (Exception e) {}
        finally {
          /* Verify the Java class path. */
          System.out.println("====================");
          System.out.println("CLASSPATH [" + System.getProperty("java.class.path") + "]");
          System.out.println("====================");
        }
      }
    }

EclipseMySQLLib_09

  1. The Save and Launch dialog informs you are saving a MysqlConnector.java file to your mysql project. Click the OK button to continue.

EclipseMySQLLib_10

  1. The next screen shows that the program successfully connected to the MySQL database by printing the following information to the Console output tab.
    ====================
    CLASSPATH [/home/student/Code/workspace/MySQL/bin:/usr/share/java/mysql-connector-java.jar]
    ====================
    ====================
    CLASSPATH [/home/student/Code/workspace/MySQL/bin:/usr/share/java/mysql-connector-java.jar]
    ====================

EclipseMySQLLib_11

  1. Instead of repeating steps #5 through #10, the image displays the testing of the MysqlResults class file. The code follows below:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    
    /* Import the java.sql.* package. */
    import java.sql.*;
     
    /* You can't include the following on Linux without raising an exception. */
    // import com.mysql.jdbc.Driver;
     
    public class MySQLResult {
      public MySQLResult() {
        /* Declare variables that require explicit assignments because
           they're addressed in the finally block. */
        Connection conn = null;
        Statement stmt = null;
        ResultSet rset = null;
     
        /* Declare other variables. */
        String url;
        String username = "student";
        String password = "student";
        String database = "studentdb";
        String hostname = "localhost";
        String port = "3306";
        String sql;
     
        /* Attempt a connection. */
        try {
          // Set URL.
          url = "jdbc:mysql://" + hostname + ":" + port + "/" + database;
     
          // Create instance of MySQL.
          Class.forName ("com.mysql.jdbc.Driver").newInstance();
          conn = DriverManager.getConnection (url, username, password);
     
          // Query the version of the database, relies on *_ri2.sql scripts.
          sql = "SELECT i.item_title, ra.rating FROM item i INNER JOIN rating_agency ra ON i.item_rating_id = ra.rating_agency_id";
          stmt = conn.createStatement();
          rset = stmt.executeQuery(sql);
     
          System.out.println ("Database connection established");
     
          // Read row returns for one column.
          while (rset.next()) {
            System.out.println(rset.getString(1) + ", " + rset.getString(2)); }
     
        }
        catch (SQLException e) {
          System.err.println ("Cannot connect to database server (SQLException):");
          System.out.println(e.getMessage());
        }
        catch (ClassNotFoundException e) {
          System.err.println ("Cannot connect to database server (ClassNotFoundException)");
          System.out.println(e.getMessage());
        }
        catch (InstantiationException e) {
          System.err.println ("Cannot connect to database server (InstantiationException)");
          System.out.println(e.getMessage());
        }
        catch (IllegalAccessException e) {
          System.err.println ("Cannot connect to database server (IllegalAccesException)");
          System.out.println(e.getMessage());
        }
        finally {
          if (conn != null) {
            try {
              rset.close();
              stmt.close();
              conn.close();
              System.out.println ("Database connection terminated");
            }
            catch (Exception e) { /* ignore close errors */ }
          }
        }
      }
      /* Unit test. */
      public static void main(String args[]) {
        new MySQLResult(); }
    }

    After you click the green arrow or the Run menu and Run menu option to compile and run the program, you should see the following output. That is if you’re using my create_mysql_store_ri2.sql and seed_mysql_store_ri2.sql files.

    Database connection established
    I Remember Mama, NR
    Tora! Tora! Tora!, G
    A Man for All Seasons, G
    Around the World in 80 Days, G
    Camelot, G
    Christmas Carol, G
    I Remember Mama, G
    The Hunt for Red October, PG
    Star Wars I, PG
    Star Wars II, PG
    Star Wars II, PG
    The Chronicles of Narnia, PG
    Beau Geste, PG
    Hook, PG
    Harry Potter and the Sorcerer's Stone, PG
    Scrooge, PG
    Harry Potter and the Sorcer's Stone, PG
    Harry Potter and the Sorcer's Stone, PG
    Harry Potter and the Chamber of Secrets, PG
    Harry Potter and the Chamber of Secrets, PG
    Harry Potter and the Prisoner of Azkaban, PG
    Harry Potter and the Prisoner of Azkaban, PG
    Harry Potter and the Half Blood Prince, PG
    Star Wars III, PG-13
    Casino Royale, PG-13
    Casino Royale, PG-13
    Die Another Day, PG-13
    Die Another Day, PG-13
    Die Another Day, PG-13
    Golden Eye, PG-13
    Golden Eye, PG-13
    Tomorrow Never Dies, PG-13
    Tomorrow Never Dies, PG-13
    The World Is Not Enough, PG-13
    Clear and Present Danger, PG-13
    Clear and Present Danger, PG-13
    Harry Potter and the Goblet of Fire, PG-13
    Harry Potter and the Goblet of Fire, PG-13
    Harry Potter and the Goblet of Fire, PG-13
    Harry Potter and the Order of the Phoenix, PG-13
    Harry Potter and the Deathly Hallows, Part 1, PG-13
    Harry Potter and the Deathly Hallows, Part 2, PG-13
    Brave Heart, R
    The Chronicles of Narnia, E
    MarioKart, E
    Need for Speed, E
    Cars, E
    RoboCop, M
    Pirates of the Caribbean, T
    Splinter Cell, T
    The DaVinci Code, T
    Database connection terminated

As always, I hope the note helps those trying to work with the Eclipse product.

Written by maclochlainn

May 10th, 2015 at 2:09 am