62,614
社区成员
发帖
与我相关
我的任务
分享
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Demo extends JFrame implements ActionListener {
private JButton button;
private Vector<Vector> vector;
private Vector columnNames;
private JTable table;
private JScrollPane jsp;
private DefaultTableModel tableModel;
public Demo() {
this.setTitle("数据库查询示例");
this.setSize(800,600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
button = new JButton("查询");
this.add(button, BorderLayout.NORTH);
button.addActionListener(this);
//调用方法初始化表格
init();
jsp = new JScrollPane(table);
this.add(jsp);
this.setVisible(true);
}
/**
* 初始化表格
*/
private void init() {
//表头
columnNames = new Vector();
String[] columns = {"学号","姓名","性别","年龄","政治面貌","籍贯","专业"};
for(int i=0; i<columns.length; i++) {
columnNames.add(columns[i]);
}
//数据
vector = new Vector<Vector>();
tableModel = new DefaultTableModel(vector,columnNames);
table = new JTable(tableModel);
}
public static void main(String[] args) {
new Demo();
}
/**
* 处理单击查询事件,用DefaultTableModel或继承AbstractTableModel自己实现模型
* 更新数据的时候,更新模型的数据,然后重新设置表格的模型,这样表格就可以显示出更新后的数据
*/
public void actionPerformed(ActionEvent e) {
try {
vector = Demo.query();
tableModel = (DefaultTableModel)table.getModel();
tableModel.setDataVector(vector, columnNames);
table.setModel(tableModel);
//下面几行可有可无,通常情况下写上就可以了
table.validate();
table.repaint();
} catch (ClassNotFoundException e1) {
JOptionPane.showMessageDialog(this, "数据库驱动加载错误!");
} catch (SQLException e1) {
JOptionPane.showMessageDialog(this, "数据库操作错误!");
}
}
/**
* 查询数据
* @return 包含数据的Vector
* @throws ClassNotFoundException
* @throws SQLException
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Vector<Vector> query() throws ClassNotFoundException, SQLException {
Vector<Vector> v = new Vector<Vector>();
String sql = "select * from student";
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;dataBaseName=student","sa","sa");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
Vector temp = new Vector();
temp.add(rs.getString("code"));
temp.add(rs.getString("name"));
temp.add(rs.getInt("sex"));
temp.add(rs.getInt("age"));
temp.add(rs.getString("political"));
temp.add(rs.getString("origin"));
temp.add(rs.getString("professional"));
v.add(temp);
}
rs.close();
stmt.close();
conn.close();
return v;
}
}