Create a JDBC Table Model #24
Chapter 3, Tables and Trees
With the queries done, you just convert the ArrayLists to real arrays (which
offer quick lookups for the get methods). The implementations of the
methods mentioned previously, as well as the improved
, are trivial uses
arrays built up by this
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
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
JTable from the model and puts it in a JFrame. Example 3-13 shows the
source for this demo.