QueryTableModel: a basic implementation of the TableModel Interface

| July 4, 2011 | 0 Comments

Here is a class that offers a basic implementation of the AbstractTableModel class:

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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.sql.*;
import java.io.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.*;
 
public class QueryTableModel extends AbstractTableModel {
Vector cache;  // will hold String[] objects . . .
int colCount;
String[] headers;
Connection db;
Statement statement;
String currentURL;
 
public QueryTableModel() {
cache = new Vector();
new gsl.sql.driv.Driver();
}
 
public String getColumnName(int i) { return headers[i]; }
public int getColumnCount() { return colCount; }
public int getRowCount() { return cache.size();}
 
public Object getValueAt(int row, int col) {
return ((String[])cache.elementAt(row))[col];
}
 
public void setHostURL(String url) {
if (url.equals(currentURL)) {
// same database, we can leave the current connection open
return;
}
// Oops . . . new connection required
closeDB();
initDB(url);
currentURL = url;
}
 
// All the real work happens here; in a real application,
// we'd probably perform the query in a separate thread.
public void setQuery(String q) {
cache = new Vector();
try {
// Execute the query and store the result set and its metadata
ResultSet rs = statement.executeQuery(q);
ResultSetMetaData meta = rs.getMetaData();
colCount = meta.getColumnCount();
 
// Now we must rebuild the headers array with the new column names
headers = new String[colCount];
for (int h=1; h <= colCount; h++) {
headers[h-1] = meta.getColumnName(h);
}
 
// and file the cache with the records from our query.  This would not be
// practical if we were expecting a few million records in response to our
// query, but we aren't, so we can do this.
while (rs.next()) {
String[] record = new String[colCount];
for (int i=0; i < colCount; i++) {
record[i] = rs.getString(i + 1);
}
cache.addElement(record);
}
fireTableChanged(null); // notify everyone that we have a new table.
}
catch(Exception e) {
cache = new Vector(); // blank it out and keep going.
e.printStackTrace();
}
}
 
public void initDB(String url) {
try {
db = DriverManager.getConnection(url);
statement = db.createStatement();
}
catch(Exception e) {
System.out.println("Could not initialize the database.");
e.printStackTrace();
}
}
 
public void closeDB() {
try {
if (statement != null) { statement.close(); }
if (db != null) {        db.close(); }
}
catch(Exception e) {
System.out.println("Could not close the current connection.");
e.printStackTrace();
}
}
}
1
 

Source: “Java Swing Second Edition” O´Really
http://www.oreilly.com/catalog/jswing2/

Tags: ,

Category: Others

Leave a Reply