请怎么利用表格显示从数据库查询的结果?
我写了个比较简单的程序用JTable显示一个指定数据库中指定table的全部数据:代码如下:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.sql.rowset.*;
/**
*用JTable来显示数据库中的数据
*@author Eastsun
*@version 0.1
*/
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;
}
其中database.properties文件的格式如下,保存在与代码相同的文件夹下
注意,我用的是Derby DB,和楼主的不一样,要把jdbc.drivers与jdbc.url改为适当的形式.
jdbc.drivers=org.apache.derby.jdbc.EmbeddedDriver
jdbc.url=jdbc:derby:F:/Java/JavaDB/myDB
jdbc.username=eastsun
jdbc.password=eastsun
jdbc.table=myTable