ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Hacking Swing: A JDBC Table Model
Pages: 1, 2, 3

Testing Things Out

Before you say "I can't run this hack, I don't have a database," relax! The open source world has you covered. And no, it's not some big thing like JBoss. HSQLDB, more commonly known by its old name, Hypersonic, is a JDBC relational database engine written in Java. It is really small and can be run as a standalone server or within your JVM. If you are database-less, grab HSQLDB from http://hsqldb.sourceforge.net/.



Whatever your database, you'll need a driver classname, URL, username, and password to make a connection to the database. If you have your own database, I trust you already know this. If you just downloaded HSQLDB one paragraph ago, then you'll be using the following information:

  • Driver: org.hsqldb.jdbcDriver

  • URL: jdbc:hsqldb:file:testdb

  • User: sa

  • Password: (none)

This assumes you'll be running Hypersonic as part of your application, meaning you'll need to extend your classpath to pick up the hsqldb.jar file. Also note that this will create some testdb files in your current directory that you can clean up when done. You can also provide a full path to some other directory; see HSQLDB's docs for more info.

The test runner expects to pick up the connection strings as properties named jdbctable.driver, jdbctable.url, jdbctable.user, and jdbctable.pass. To make things easier, there are two ways to pass these in: either as system properties (usually specified with -D arguments to the java command), or in a file called jdbctable.properties. The book code has a sample of the latter with HSQLDB values as defaults.

To test the JDBCTableModel, the TestJDBCTable creates an entirely new table in the database. The model gets the Connection and the name of this table and loads the data from the database. Then the test class simply creates a new JTable from the model and puts it in a JFrame. Example 3-13 shows the source for this demo.

Example 3-13. Testing the JDBC-based table


		import javax.swing.*; 
	import javax.swing.table.*; 
	import java.sql.*; 
	import java.util.*; 
	import java.io.*;
	public class TestJDBCTable {
		public static void main (String[] args) {
			try {

		/* 
		 driver, url, user, and pass can be passed in as 
		 system properties "jdbctable.driver", 
		 "jdbctable.url", "jdbctable.user", and 
		 "jdbctable.pass", or specified in a file 
		 called "jdbctable.properties" in current 
		 directory
		*/
		Properties testProps = new Properties();
		String ddriver = System.getProperty ("jdbctable.driver");
		String durl = System.getProperty ("jdbctable.url");
		String duser = System.getProperty ("jdbctable.user");
		String dpass = System.getProperty ("jdbctable.pass");

		if (ddriver != null) 
			testProps.setProperty ("jdbctable.driver", ddriver); 
		if (durl != null) 
			testProps.setProperty ("jdbctable.url", durl); 
		if (duser != null) 
			testProps.setProperty ("jdbctable.user", duser);
		if (dpass != null) 
			testProps.setProperty ("jdbctable.pass", dpass);
		try { 
			testProps.load (new FileInputStream (
					new File ("jdbctable.properties"))); 
		} catch (Exception e) {} // ignore FNF, etc. 
		System.out.println ("Test Properties:"); 
		testProps.list (System.out);
		// now get a connection 
		// note care to replace nulls with empty strings 
		Class.forName(testProps.getProperty
				("jdbctable.driver")).newInstance();
		String url = testProps.getProperty ("jdbctable.url");
		url = ((url == null) ? "" : url); 
		String user = testProps.getProperty ("jdbctable.user"); 
		user = ((user == null) ? "" : user); 
		String pass = testProps.getProperty ("jdbctable.pass"); 
		pass = ((pass == null) ? "" : pass);

		Connection conn = 
			DriverManager.getConnection (url, user, pass);
		// create db table to use
		String tableName = createSampleTable(conn);

		// get a model for this db table and add to a JTable
		TableModel mod =
			new JDBCTableModel (conn, tableName);
		JTable jtable = new JTable (mod);
		JScrollPane scroller =
			new JScrollPane (jtable, 
				ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, 
				ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		JFrame frame = new JFrame ("JDBCTableModel demo");
		frame.getContentPane().add (scroller);
		frame.pack();
		frame.setVisible (true);

		conn.close();

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

		public static String createSampleTable (Connection conn)
			throws SQLException {

			Statement statement = conn.createStatement();
			// drop table if it exists
			try {

		statement.execute ("DROP TABLE EMPLOYEES");
			} catch (SQLException sqle) {
		sqle.printStackTrace(); // if table !exists
			}
			
			statement.execute ("CREATE TABLE EMPLOYEES " + 
				   "(Name CHAR(20), Title CHAR(30), Salary INT)"); 
			statement.execute ("INSERT INTO EMPLOYEES VALUES " + 
				   "('Jill', 'CEO', 200000 )"); 
			statement.execute ("INSERT INTO EMPLOYEES VALUES " + 
				   "('Bob', 'VP', 195000 )"); 
			statement.execute ("INSERT INTO EMPLOYEES VALUES " + 
				       "('Omar', 'VP', 190000 )"); 
			statement.execute ("INSERT INTO EMPLOYEES VALUES " + 
				   "('Amy', 'Software Engineer', 50000 )"); 
			statement.execute ("INSERT INTO EMPLOYEES VALUES " + 
				   "('Greg', 'Software Engineer', 45000 )");

	     statement.close();
		 return "EMPLOYEES"; 
		 }
	}

The createSampleTable() method is something you could rewrite to insert your own types and values easily. In fact, because it returns the name of the table you've created, you could create many different tables in your database and test out how the model handles them. Or, use a loop to create lots of rows and see how long it takes to load them.

At any rate, when run, the TestJDBCTable produces a JFrame with the database table's contents, as seen in Figure 3-9.

Figure 3-9
Figure 3-9. JTable populated from a database

Joshua Marinacci is a blogger and co-author of "Swing Hacks" and "Building Mobile Apps with Java" for O'Reilly.

Chris Adamson is an author, editor, and developer specializing in iPhone and Mac.


View catalog information for Swing Hacks

Return to ONJava.com.