public String []columnNames={"病人ID","病人姓名","病人年龄","病人性别","出生日期","出生地","籍贯","情况","费用"};//定义数组
private JScrollPane JScrollPane1=new JScrollPane();
private static JTable table;
private static DefaultTableModel dtm;
Connection con;
jdbc connect=new jdbc(); //连接数据库
con=connect.getConnection();
//得到用户名重的要查询的内容
String sql="select * from Hospital_Patient" ; //SQL语句
ResultSet rs;// 创建结果集
、
JScrollPane1.setBounds(new Rectangle(0,50,1000,185)); //滚动条的创建
Jpanel.add(JScrollPane1); //添加到面板上
defaultTableModel(); //调用函数
JScrollPane1.setViewportView(table); //可见
try{
}catch(Exception e1){
e1.printStackTrace();
}
try{
int row = dtm.getRowCount() - 1;
if (row != -1) {
for (int i1 = row; i1 >= 0; i1--) {
dtm.removeRow(i1); // 删除Jtable中的所有行
}
dtm.setRowCount(0); // 将Jtable中的行数设为零
}
Statement stmt=con.createStatement();
rs=stmt.executeQuery(sql);//执行SQL语句
String[] data = new String[9];
while (rs.next()) {
for (int j = 1; j <= 9; j++) {
data[j - 1] = rs.getString(j); // 取出数据库中的数组装载到数组中
}
dtm.addRow(data); // 在Jtable中添加
}
con.close();
}catch(Exception err){
String error=err.getMessage();
JOptionPane.showMessageDialog(null, error);
err.printStackTrace();
}finally{
connect.closeConnection();
}
private void defaultTableModel() {//添加默认表格以及设置单元格不能编辑
// TODO Auto-generated method stub
dtm=new DefaultTableModel(columnNames,0); //添加首行元素数据
table=new JTable(dtm){
public boolean isCellEditable(int row, int column)
{
return false;
}//表格不允许被编辑 }
};
}