Java Reference
In-Depth Information
142
143 // set new database query string
144 public void setQuery(String query)
145 throws SQLException, IllegalStateException
146 {
147 // ensure database connection is available
148 if (!connectedToDatabase)
149 throw new IllegalStateException( "Not Connected to Database" );
150
151 // specify query and execute it
152 resultSet = statement.executeQuery(query);
153
154 // obtain metadata for ResultSet
155 metaData = resultSet.getMetaData();
156
157 // determine number of rows in ResultSet
158 resultSet.last(); // move to last row
159 numberOfRows = resultSet.getRow(); // get row number
160
161
162
163 }
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187 } // end class ResultSetTableModel
// notify JTable that model has changed
fireTableStructureChanged();
// close Statement and Connection
public void disconnectFromDatabase()
{
if (connectedToDatabase)
{
// close Statement and Connection
try
{
resultSet.close();
statement.close();
connection.close();
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
}
finally // update database connection status
{
connectedToDatabase = false ;
}
}
}
Fig. 24.25 | A TableModel that supplies ResultSet data to a JTable . (Part 4 of 4.)
ResultSetTableModel Constructor
The ResultSetTableModel constructor (lines 30-46) accepts four String arguments—
the URL of the database, the username, the password and the default query to perform.
The constructor throws any exceptions that occur in its body back to the application that
created the ResultSetTableModel object, so that the application can determine how to
Search WWH ::




Custom Search