/*
*
* 这是我的一个stu表的模型
* 可以把对studnet的各种表进行封装
* */
package com.test1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.*;
public class StuModel extends AbstractTableModel {
//定义操作数据库需要的
Vector rowData,columnNames;
PreparedStatement ps=null;
ResultSet rs=null;
Connection ct=null;
//通过传递的sql语句来获得模型
public void init(String sql)
{
if(sql.equals(""))
{
sql="select *from stu";
}
columnNames=new Vector();
columnNames.add("学号");
columnNames.add("名字");
columnNames.add("性别");
columnNames.add("年龄");
columnNames.add("籍贯");
columnNames.add("系别");
rowData=new Vector();
try
{
//加载驱动
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
//得到连接
ct=DriverManager.getConnection("jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=test1","buptwqp","314329");
//火箭车
ps=ct.prepareStatement(sql);
//执行
rs=ps.executeQuery();
while(rs.next())
{
Vector hang=new Vector();
hang.add(rs.getString(1));
hang.add(rs.getString(2));
hang.add(rs.getString(3));
hang.add(rs.getInt(4));
hang.add(rs.getString(5));
hang.add(rs.getString(6));
rowData.add(hang);
}
//初始化jtable
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
//关闭资源
try{
if(rs!=null)
{
rs.close();
}
if(ct!=null)
{
ct.close();
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public void addStu(String sql)
{
//根据用户输入的sql语句完成添加
}
//做一个构造函数
public StuModel()
{
this.init("");
}
public StuModel(String sql)
{
this.init(sql);
}
//得到共有多少列
public int getColumnCount() {
// TODO Auto-generated method stub
return this.columnNames.size();
}
//得到共有多少行
public int getRowCount() {
// TODO Auto-generated method stub
return this.rowData.size();
}
//得到某行某列的数据
public Object getValueAt(int row, int column) {
// TODO Auto-generated method stub
return ((Vector)this.rowData.get(row)).get(column);
}
@Override
public String getColumnName(int column) {
// TODO Auto-generated method stub
return (String)this.columnNames.get(column);
}
}
Java的抽象表模型,为一张表建一个模型,方便显示读取数据