Step 10.6: Running the HelloHSQL class


Step 10.6: Running the HelloHSQL class

click to expand

Run the class from the Run menu of the Eclipse main menu bar.

q 10.6(a) Select the HelloHSQL class by left-clicking on it.

q 10.6(b) From the Run tool, select Run As/Java Application.

click to expand
Figure 10.25: Running HelloHSQL as a Java Application.

This will create a launch configuration for HelloHSQL with the default characteristics and then attempt to run it.

Once again, you won't meet with a lot of success, as you can see in Figure 10.26. And even though the console view is rather small, the error is pretty compact and very concise : ClassNotFoundException: org.hsqldb.jdbcDriver.

click to expand
Figure 10.26: Blue text is system console output ”this is your own error routine and it shows that you're missing HSQLDB's JAR file.

This is actually a very common error during JDBC programming, and it just means that you haven't yet added the SQL engine's JAR file to your classpath, which you can do immediately.

q 10.6(c) Right-click on the SWT Project.

click to expand
Figure 10.27: Using the popup menu to access the properties dialog for the SWT project.

The classpath is on the Java Build Path properties sheet, under the Libraries tab. You should already be there, but if not:

q 10.6(d) Select the Java Build Path properties sheet.

q 10.6(e) Select the Libraries tab.

Add the JAR file by using the Add External JARs button.

q 10.6(f) Click 'Add External JARs. . .'

click to expand
Figure 10.28: Click Add External JARs ...

A standard file finder dialog will appear. It will probably be in the win32 folder; that's the last folder you imported a JAR file from.

click to expand
Figure 10.29: The last folder you added a JAR file from.

Navigate to where you installed HSQLDB in Step 10.1.

Note  

If you're using a database other than HSQLDB, you will need to include your own JAR file in these next steps.

q 10.6(g) Type 'C:\Program Files\SQL' into the File name field and click Open .

click to expand
Figure 10.30: Open the SQL folder where you installed HSQLDB back in Step 10.1.

Next, open the HSQLDB folder (which should be named hsqldb).

q 10.6(h) Open the folder named hsqldb.

click to expand
Figure 10.31: Open the hsqldb folder.

q 10.6(i) Open the folder named lib.

click to expand
Figure 10.32: Open the lib folder.

Now you will have reached a point where you see a JAR file named hsqldb.jar. This is the JAR file that you want to include on your classpath.

q 10.6(j) Open the file named hsqldb.jar.

click to expand
Figure 10.33: Open hsqldb.jar, which includes it in the classpath.

You'll see that the JAR file has been added to the Libraries tab. Just click OK to continue.

q 10.6(k) Click OK.

click to expand
Figure 10.34: The new JAR file is in the Libraries tab, so press OK.

Your workbench should now look like the one in Figure 10.35. Interestingly, there are still some warning messages. But if you'll look closely, you'll see that while you got rid of all the errors for HelloHSQL, the old warnings for HelloSWT popped up again. This could be a little confusing, so always watch this list carefully .

click to expand
Figure 10.35: No errors.

q 10.6(1) Click the Run tool to rerun HelloHSQL.

click to expand
Figure 10.36: Hitting the run tool reruns the last application, which in this case is HelloHSQL.

You will see the screen below. Notice that records for DOG, CAT, and OCTOPUS have all been entered. Congratulations!

click to expand
Figure 10.37: Output from the HelloHSQL class.

Code review: HelloHSQL

 import java.sql.*; 

This is the standard import command for JDBC programs; it defines the primary JDBC classes such as Driver, Connection, and Statement.

 public class HelloHSQL { 

This is standard code for any runnable Java application.

 private static final String SQLCLASS = "org.hsqldb.jdbcDrive-"; private static final String SQLURL   = "jdbc:hsqldb:hsqldb"; private static final String SQLUSER  = "sa"; private static final String SQLPWD   = ""; 

These are the JDBC constants. I go into them in some detail in Step 10.5. In general, the class and URL are determined by the SQL engine vendor, while the user ID and password are up to you. In this particular case, however, the user ID "sa" is a special user ID for the HSQLDB product ”it will initialize the database if it does not already exist. So please don't change this code unless you're very comfortable with what you're doing.

 public static void main(String[] args) { 

More standard Java application code.

 try { 

Note that all of the SQL code is inside a try/catch block. This is the standard Java technique for checking for errors in called methods . The called method will "throw" an exception, and the calling method will "catch" it. This technique is very powerful, but it can sometimes lead to complicated code (an example of which I'll show you in a moment). This particular try block, however, is pretty straightforward ”it encompasses all the code in the main method; the catch is at the bottom of the code.

 // Create a connection Class.forName (SQLCLASS); Connection c = DriverManager.getConnection(SQLURL, SQLUSER, SQLPWD); Statement s = c.createStatement(); 

This code is very standard, although it's not exactly intuitive. The Class.forName() call causes a static initializer to be invoked, which registers the driver. For my tastes, this is a "clever" technique, and "clever" is not a compliment. In programming, "clever" code usually indicates code that is nonintuitive and may be easy to misunderstand. The only saving grace is that every JDBC vendor does this, so once you learn this particular technique, you'll find that it applies to every JDBC a pplication.

After that, the code simply creates a Connection, which represents a communication session with the host, and a Statement, which is used to execute SQL requests and return result sets when appropriate.

Up until this point, the code for every JDBC application is the same, or at least similar. There may be some minor differences as to runtime attributes or perhaps some slightly different code to take advantage of connection pooling, but in general, the idea is always the same: Instantiate the driver, open the connection, create a statement.

 // Delete and recreate the table try {       s.execute("DROP TABLE ITEMS"); } catch (Exception e) {} s.execute("CREATE TABLE ITEMS (ItemNumber CHAR, Description CHAR)"); 

This is the start of the application-specific code. The DROP command is used to delete an SQL table, while CREATE builds a new one. This is pretty low-level code, and wouldn't normally be part of a day-to-day application, but since you're starting from scratch, you're going to have to create the table sometime, and you may as well do it in a program ”this tests that you have everything installed properly.

Take a close look at the line that executes the DROP command. You'll notice that there is a try/catch block around it. That's because the DROP is going to fail the first time you run this program (the table won't exist yet!), and the primary way that JDBC reports errors back to the user for these types of commands is through exceptions. Since the code is already inside a try/catch block, the not-found error would cause the program to end. So instead, I've put a nested try/catch block around just the DROP command. In this block, I ignore any errors. In a production application I would only catch for SQLException and verify that the error is "Table Not Found". If it wasn't, I'd throw the error to the higher level try/catch.

 // Insert data s.execute("INSERT INTO ITEMS VALUES ('DOG', 'Cuddly Duddly')"); s.execute("INSERT INTO ITEMS VALUES ('CAT', 'Felix the Cat')"); s.execute("INSERT INTO ITEMS VALUES ('OCTOPUS', 'Squidworth')"); 

These statements populate the table using the standard JDBC1 syntax. In JDBC1, all commands other than the SELECT statement are run using the execute method. JDBC2, on the other hand, allows more traditional record-based access, where you can position yourself in a file, update fields and then rewrite a record.

HSQLDB doesn't support the more powerful JDBC2 syntax. If you look through the SideStep, however, you'll find some examples of code that does take advantage of JDBC2. The SAPDB and the JTOpen drivers both support JDBC2.

 // Check the results ResultSet rs = s.executeQuery("SELECT * FROM ITEMS"); while (rs.next()) {       System.out.println(             "Item: " + rs.getString("ItemNumber") +             ", Description: " + rs.getString("Description")); } 

This is a standard JDBC read loop. In JDBC, you create a ResultSet, which represents a set of rows in a specified order. The "next" method moves to the next record in the set, and returns false if there are no more. The getString method allows you to retrieve the value of a field as an object of type String. There are other methods available to get numeric data and so on, but the general idea is still the same: get the next row, extract out the columns using get Xxx methods, and loop until done.

 // Shut down s.close(); c.close(); 

At the end of the day, you need to clean up. This is especially important in distributed systems; not performing the appropriate shutdown steps can leave connections open and waste resources on the host. Always close your statement and your connection.

(In fact, you should probably use a finally clause in your try/catch block to shut down the connection if anything goes wrong, but that's a little bit outside the scope of this particular program.)

 } catch (Exception e) {       System.out.println("Error: " + e); } 

Here's the standard catch block. I'm not doing anything fan ”I just print the error message.

 // When done, clean up resource and exit            System.exit(0);     } } 

And finally, good Java programming practices dictate that an application always ends with System.exit(0). That's it for this program.




Eclipse
Eclipse: Step by Step (Step-by-Step series)
ISBN: 1583470441
EAN: 2147483647
Year: 2003
Pages: 90
Authors: Joe Pluta

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net