How to view database resultset in Java swing

萝らか妹 提交于 2019-12-13 06:01:00

问题


How to view database resultset in Java swing? My options are

  1. jeditorpane
  2. jtable.

After view that file i want to save the file either in .rtf or .pdf. how is this possible in Java desktop apps?

Note: Do not use third party API or libraries


回答1:


Viewing your result - JTable is your best choice

Saving the results, well, unless you want to use a 3rd part library, you options are very limited, unless your very familiar with the various file formats you want to use.

Out of the box, I'd say CVS would be easy to achieve.




回答2:


JTable will do best, here is the code for display ResultSet on JTable

public static void main(String[] args) throws Exception {
// The Connection is obtained

ResultSet rs = stmt.executeQuery("select * from product_info");

// It creates and displays the table
JTable table = new JTable(buildTableModel(rs));
JOptionPane.showMessageDialog(null, new JScrollPane(table)); // or can you other swing component

// Closes the Connection
}

The method buildTableModel:

public static DefaultTableModel buildTableModel(ResultSet rs)
    throws SQLException {

ResultSetMetaData metaData = rs.getMetaData();

// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
    columnNames.add(metaData.getColumnName(column));
}

// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
    Vector<Object> vector = new Vector<Object>();
    for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
        vector.add(rs.getObject(columnIndex));
    }
    data.add(vector);
}

return new DefaultTableModel(data, columnNames);

}

it would be hard to export data to pdf or rtf without using 3rd party api



来源:https://stackoverflow.com/questions/11734561/how-to-view-database-resultset-in-java-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!