/**
* 从数据库中取出学生信息
*/
package com.jdbc;
import javax.swing.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Demo7 extends JFrame {
//rowDate用来存放行数据,columnNames存放列名
Vector rowDate,columnNames;
JTable jt=null;
JScrollPane jsp=null;
//定义操作数据库需要的东西
PreparedStatement ps=null;
Connection ct=null;
ResultSet rs=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo7 demo7=new Demo7();
}
public Demo7()
{
columnNames=new Vector();
//设置列名
columnNames.add("学号");
columnNames.add("姓名");
columnNames.add("性别");
columnNames.add("生日");
columnNames.add("记过次数");
//rowDate可以存放多行
rowDate=new Vector();
try {
//加载驱动
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
ct=DriverManager.getConnection("jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=aa ","sa","910526");
ps=ct.prepareStatement("select * from stu");
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));
//加入到rowDate
rowDate.add(hang);
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}finally{
try {
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(ct!=null) ct.close();
} catch (Exception e2) {
e2.printStackTrace();
// TODO: handle exception
}
}
//初始化JTable
jt=new JTable(rowDate,columnNames);
//初始化JScrolPane
jsp=new JScrollPane(jt);
//把jsp放入到JFrame
this.add(jsp);
this.setSize(400, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
|
|