重新措辞这个问题,因为它不是很清楚。我的问题是,每当 generateReport 方法尝试使用 model.getColumnCount() 时,它都会返回零并给出 ResultSet is Closed 错误。
但是,如果我删除该 finally 块,一切都会按预期工作。如何通过关闭连接正确执行此操作?
我是否认为该模型仅存在于我使用过的 createTable 方法中
model = new ResultSetTableModel(rs);
即使我将模型声明为类变量?
创建 JTable 的方法
private void createTable() {
databaseName = (txtQueryDatabase.getText());
String sql = txtQueryString.getText();
openDatabase();
try {
ResultSet rs = stmt.executeQuery(sql);
model = new ResultSetTableModel(rs);
tblEmployee.setModel(model);
txtQueryCount.setText(Integer.toString(model.getRowCount()));
} catch (SQLException e) {
errorMessage(e);
} catch (Exception e) {
errorMessage(e);
} finally {
closeDatabase();
}
写入文件的方法
private void generateReport(File file) throws IOException {
file.createNewFile();
BufferedWriter bfw = new BufferedWriter(new FileWriter(file));
for (int i = 0; i < model.getColumnCount(); i++) {
bfw.write(model.getColumnName(i));
bfw.write(" | ");
}
for (int i = 0; i < model.getRowCount(); i++) {
bfw.newLine();
for (int j = 0; j < model.getColumnCount(); j++) {
bfw.write(model.getValueAt(i, j).toString());
bfw.write(" | ");
}
}
bfw.close();
}
ResultSetTableModel 类
public ResultSetTableModel(ResultSet aResultSet) {
try {
rs = aResultSet;
rsmd = rs.getMetaData();
data = new ArrayList<Object>();
while (rs.next()) {
Object[] row = new Object[rsmd.getColumnCount()];
for (int i = 0; i < row.length; i++) {
row[i] = rs.getObject(i + 1);
}
data.add(row);
}
} catch (SQLException e) {
message.errorMessage(e);
}
}
@Override
public Object getValueAt(int row, int col) {
if (row < data.size()) {
return ((Object[]) data.get(row))[col];
} else {
return null;
}
}
@Override
public int getRowCount() {
return data.size();
}
@Override
public String getColumnName(int count) {
try {
return rsmd.getColumnName(++count);
} catch (SQLException e) {
message.errorMessage(e);
return "";
}
}
@Override
public int getColumnCount() {
try {
return rsmd.getColumnCount();
} catch (SQLException e) {
message.errorMessage(e);
return 0;
}
}
}