我想从DefaultTableModel
创建ResultSet
。为此,我需要Object[][]
。
为此,我必须在遍历表格之前指定对象的size
:我转到rs.last()
,然后转到rs.getRow()
,然后转到rs.beforeFirst()
;
之后,rs.next()
不会在while
周期内执行。
我做错了什么?
public static DefaultTableModel buildTableModel(ResultSet _resultSet) {
ResultSetMetaData metaData;
Object[] columnNames = null;
Object[][] tableData = null;
int columnCount;
int currentRowNumber = 0;
try {
metaData = _resultSet.getMetaData();
columnCount = metaData.getColumnCount();
columnNames = new Object[columnCount];
_resultSet.last();
tableData = new Object[_resultSet.getRow()][columnCount];
_resultSet.beforeFirst();
for (int currentColumn = 0; currentColumn <= columnCount; currentColumn++) {
columnNames[currentColumn] = metaData.getColumnName(currentColumn + 1);
}
while (_resultSet.next()) {
for (int columnIndex = 0; columnIndex <= columnCount; columnIndex++) {
tableData[currentRowNumber][columnIndex] = _resultSet.getObject(columnIndex + 1);
}
currentRowNumber++;
}
} catch (SQLException ex) {
System.out.println("bad");
}
return new DefaultTableModel(tableData, columnNames);
}
答案 0 :(得分:2)
可能您的ResultSet
不是滚动不敏感的,也就是说,它只能向前遍历。
请参阅文档here:
[...]默认的ResultSet对象不可更新,并且只有一个向前移动的游标。因此,您只能迭代一次,并且只能从第一行到最后一行。 [...]
要创建双向,请执行以下操作:
Connection conn = DriverManager.getConnection(...);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ...);
ResultSet rset = stmt.executeQuery(sql);
答案 1 :(得分:1)
首先,您需要从ResultSetMetaData
打印列名称。比你申请_resultSet.last();
和_resultSet.beforeFirst();
。这样它就一直在我的机器上工作。
public static DefaultTableModel buildTableModel(ResultSet _resultSet) {
ResultSetMetaData metaData;
Object[] columnNames = null;
Object[][] tableData = null;
int columnCount;
int currentRowNumber = 0;
try {
metaData = _resultSet.getMetaData();
columnCount = metaData.getColumnCount();
columnNames = new Object[columnCount];
// Print column here.
for (int currentColumn = 0; currentColumn <= columnCount; currentColumn++) {
columnNames[currentColumn] = metaData.getColumnName(currentColumn + 1);
}
tableData = new Object[_resultSet.getRow()][columnCount];
//Here point resultSet cursor to last and beforeFirst.
_resultSet.last();
_resultSet.beforeFirst();
// After swaping the above part. Now it will enter on while loop.
while (_resultSet.next()) {
for (int columnIndex = 0; columnIndex <= columnCount; columnIndex++) {
tableData[currentRowNumber][columnIndex] = _resultSet.getObject(columnIndex + 1);
}
currentRowNumber++;
}
} catch (SQLException ex) {
System.out.println("bad");
}
return new DefaultTableModel(tableData, columnNames);
}