请怎么利用表格显示从数据库查询的结果?
请怎么利用表格显示从数据库查询的结果?
我写了个比较简单的程序用JTable显示一个指定数据库中指定table的全部数据:代码如下:
public class ShowDataBase{
public static void main(String[] args)throws Throwable{
new DataBaseFrame();
}
}
class DataBaseFrame extends JFrame{
public ResultSet getResultSet()
throws SQLException, IOException{
Properties props = new Properties();
FileInputStream in = new FileInputStream("database.properties"); //注意:数据库的属性都保存在database.properties文件中
props.load(in);
in.close();
String drivers = props.getProperty("jdbc.drivers");
if (drivers != null) System.setProperty("jdbc.drivers", drivers);
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
Connection conn = DriverManager.getConnection(url, username, password);
String table =props.getProperty("jdbc.table");
Statement stat =conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE ,ResultSet.CONCUR_READ_ONLY );
ResultSet result =stat.executeQuery("SELECT * FROM "+table);
return result;
}
public DataBaseFrame()throws Throwable{
super("ShowDataBase");
ResultSet rs =getResultSet();
ResultSetTableModel model =new ResultSetTableModel(rs);
JTable table = new JTable(model);
add(table);
setSize(600,400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
}
//下面这个类是代码的关键
class ResultSetTableModel extends AbstractTableModel{
public ResultSetTableModel(ResultSet aResultSet){
rs = aResultSet;
try{
rsmd = rs.getMetaData();
}
catch(SQLException e){
e.printStackTrace();
}
}
public String getColumnName(int c){
try{
return rsmd.getColumnName(c + 1);
}
catch (SQLException e){
e.printStackTrace();
return "";
}
}
public int getColumnCount(){
try{
return rsmd.getColumnCount();
}
catch (SQLException e){
e.printStackTrace();
return 0;
}
}
public Object getValueAt(int r, int c){
try{
rs.absolute(r + 1);
return rs.getObject(c + 1);
}
catch(SQLException e){
e.printStackTrace();
return null;
}
}
public int getRowCount(){
try{
rs.last();
return rs.getRow();
}
catch(SQLException e){
e.printStackTrace();
return 0;
}
}
private ResultSet rs;
private ResultSetMetaData rsmd;
}