I have created an extension of JTable
, called ResultSetTable
, to display any SQL ResultSet
. It first gets the column names by looking at the meta data of the result set and then builds the table.
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
* A JTable used to display a SQL ResultSet.
* @author fahdshariff
*
*/
public class ResultSetTable extends JTable{
private final DefaultTableModel dataModel;
public ResultSetTable(ResultSet rs)
throws SQLException{
super();
dataModel = new DefaultTableModel();
setModel(dataModel);
try {
//create an array of column names
ResultSetMetaData mdata = rs.getMetaData();
int colCount = mdata.getColumnCount();
String[] colNames = new String[colCount];
for (int i = 1; i <= colCount; i++) {
colNames[i - 1] = mdata.getColumnName(i);
}
dataModel.setColumnIdentifiers(colNames);
//now populate the data
while (rs.next()) {
String[] rowData = new String[colCount];
for (int i = 1; i <= colCount; i++) {
rowData[i - 1] = rs.getString(i);
}
dataModel.addRow(rowData);
}
}
finally{
try {
rs.close();
}
catch (SQLException ignore) {
}
}
}
}
Hello Fahd. I have been breaking my head for almost 2 days and was searching for exactly this. Your Blog is very informative, simple humble and professional ;-) Keep going. Thanks for the info ;-) Saj
ReplyDeletecan you post the full code with the main method and also the connection. it would be much helpful for the beginners.
ReplyDeletestmt = conn.createStatement ();
Deleterset = stmt.executeQuery("YOUR SQL QUERY");
ResultSetTable rst = new ResultSetTable(rset);
add(rst);
Very handy, thanks!
ReplyDeleteThanks!
ReplyDeletecan this retrieve images?
ReplyDeleteThanks that seem like the code i need. I yet not applied but still feeling the it is the right one
ReplyDeleteHi can this class be changed to work as a method? to be called on an action event?
ReplyDeletethanks a lot...
ReplyDeletewhen you write this info , if you give preview image it will be better solution...
thanx!!
ReplyDeletethis is awesome. thanks a lot!!
ReplyDelete