package test;
import java.util.*;
import javax.swing.*;
import java.sql.*;
public class DataBaseDemo extends JFrame{
private Vector rowData, columnName;
private JTable jt = null;
private JScrollPane jsp = null;
//定义操作数据库所需要的对象
private PreparedStatement ps = null;
Connection ct = null;
ResultSet rs = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
DataBaseDemo dbd = new DataBaseDemo();
}
public DataBaseDemo(){
try{
//加载驱动
//com.microsoft.sqlserver.jdbc.SQLServerDriver
//jdbc:sqlserver://127.0.0.1:1433;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
ct = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;databaseName=学生管理系统", "sa", "tu520");
ps = ct.prepareStatement("select * from studentSys");
rs = ps.executeQuery();
columnName = new Vector();
//设置列名
columnName.add("学号");
columnName.add("名字");
columnName.add("性别");
columnName.add("年龄");
columnName.add("籍贯");
columnName.add("爱好");
rowData = new Vector();
while(rs.next()){
Vector line1 = new Vector();
line1.add(rs.getString(1));
line1.add(rs.getString(2));
line1.add(rs.getString(3));
line1.add(String.valueOf(rs.getInt(4)));
line1.add(rs.getString(5));
line1.add(rs.getString(6));
rowData.add(line1);
}
//初始化JTable
jt = new JTable(rowData, columnName);
jsp = new JScrollPane(jt);
this.add(jsp);
this.setTitle("你好啊!");
this.setSize(260, 150);
this.setLocation(300, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭数据库
try{
if(rs != null)rs.close();
if(ps != null)ps.close();
if(ct != null)ct.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}