📄 studentmanager.java
字号:
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class StudentManager extends JFrame{
private Connection dbConn;
private PreparedStatement ps;
private ResultSet rs;
private ResultSetMetaData rsMetaData;
//GUI变量定义
private JTable table;
private JTextArea inputQuery;
private JButton submitQuery;
Container c=getContentPane();
public StudentManager()
{
//Form的标题
super("学生管理");
final String dbURL="jdbc:sqlserver://localhost:1433; DatabaseName=sample";
final String username="sa";
final String password="2005";
//加载驱动程序以连接数据库
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
dbConn=DriverManager.getConnection(dbURL,username,password);
}catch(ClassNotFoundException cnfex){
System.err.println("装载 JDBC/ODBC 驱动程序失败。");
cnfex.printStackTrace();
System.exit(1); // terminate program
}catch(SQLException sqlex){
System.err.println( "无法连接数据库" );
sqlex.printStackTrace();
System.exit(1); // terminate program
}
//如果数据库连接成功,则建立GUI
JPanel topPanel = new JPanel();
GridBagLayout lay=new GridBagLayout();
GridBagConstraints constraints=new GridBagConstraints();
topPanel.setLayout(lay);
//Button ok_button=new Button("确定");
JButton modify_button=new JButton("修改");
JButton exit_button=new JButton("退出");
JButton add_button=new JButton("添加");
JButton delete_button=new JButton("删除");
JLabel studentno_label=new JLabel("学生学号: ");
final JTextField studentno_textfield=new JTextField();
JLabel studentname_label=new JLabel("学生姓名: ");
final JTextField studentname_textfield=new JTextField();
JLabel userinfo_label=new JLabel("班级信息:");
constraints.anchor=GridBagConstraints.CENTER;
constraints.gridx=0;
constraints.gridy=0;
constraints.weightx=1;
constraints.weighty=1;
constraints.gridwidth=1;
constraints.gridheight=1;
constraints.fill=GridBagConstraints.NONE;
constraints.anchor=GridBagConstraints.EAST;
topPanel.add(studentno_label,constraints);
constraints.gridx=1;
constraints.gridy=0;
constraints.weightx=1;
constraints.weighty=2;
constraints.gridwidth=1;
constraints.gridheight=1;
constraints.fill=GridBagConstraints.BOTH;
constraints.anchor=GridBagConstraints.CENTER;
topPanel.add(studentno_textfield,constraints);
constraints.gridx=2;
constraints.gridy=0;
constraints.weightx=1;
constraints.weighty=1;
constraints.gridwidth=1;
constraints.gridheight=1;
constraints.fill=GridBagConstraints.NONE;
constraints.anchor=GridBagConstraints.CENTER;
topPanel.add(modify_button,constraints);
constraints.gridx=0;
constraints.gridy=1;
constraints.weightx=1;
constraints.weighty=1;
constraints.gridwidth=1;
constraints.gridheight=1;
constraints.fill=GridBagConstraints.NONE;
constraints.anchor=GridBagConstraints.EAST;
topPanel.add(studentname_label,constraints);
constraints.gridx=1;
constraints.gridy=1;
constraints.weightx=1;
constraints.weighty=2;
constraints.gridwidth=1;
constraints.gridheight=1;
constraints.fill=GridBagConstraints.BOTH;
constraints.anchor=GridBagConstraints.CENTER;
topPanel.add(studentname_textfield,constraints);
/*constraints.gridx=2;
constraints.gridy=1;
constraints.weightx=1;
constraints.weighty=1;
constraints.gridwidth=1;
constraints.gridheight=1;
constraints.fill=GridBagConstraints.NONE;
constraints.anchor=GridBagConstraints.CENTER;
topPanel.add(ok_button,constraints);*/
constraints.gridx=2;
constraints.gridy=1;
constraints.weightx=1;
constraints.weighty=2;
constraints.gridwidth=1;
constraints.gridheight=1;
constraints.fill=GridBagConstraints.NONE;
constraints.anchor=GridBagConstraints.CENTER;
topPanel.add(exit_button,constraints);
constraints.gridx=0;
constraints.gridy=3;
constraints.weightx=1;
constraints.weighty=1;
constraints.gridwidth=2;
constraints.gridheight=1;
constraints.fill=GridBagConstraints.NONE;
constraints.anchor=GridBagConstraints.CENTER;
topPanel.add(add_button,constraints);
constraints.gridx=1;
constraints.gridy=3;
constraints.weightx=1;
constraints.weighty=1;
constraints.gridwidth=2;
constraints.gridheight=1;
constraints.fill=GridBagConstraints.NONE;
constraints.anchor=GridBagConstraints.CENTER;
topPanel.add(delete_button,constraints);
//按钮的单击事件处理
/*ok_button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});*/
modify_button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String[] temp={"",""};
temp[0]=studentno_textfield.getText();
temp[1]=studentname_textfield.getText();
if(temp[0].equals("")||temp[1].equals("")){
JOptionPane.showMessageDialog(new JFrame(),"空值,不合法","警告",JOptionPane.WARNING_MESSAGE);
}else if(temp[0].length()!=11){
JOptionPane.showMessageDialog(new JFrame(),"学号,不合法","警告",JOptionPane.WARNING_MESSAGE);
}else{
try{
dbConn=DriverManager.getConnection(dbURL,username,password);
String updateStr="update student set sno=?,sname=? WHERE sno=?";
String selectStr="select * from student where sno=? or sname=?";
ps=dbConn.prepareStatement(selectStr);
ps.setString(1,studentno_textfield.getText());
ps.setString(2,studentname_textfield.getText());
rs=ps.executeQuery();
if(rs.next()){
ps=dbConn.prepareStatement(updateStr);
ps.setString(1,studentno_textfield.getText());
ps.setString(2,studentname_textfield.getText());
ps.setString(3,studentno_textfield.getText());
ps.executeUpdate();
JOptionPane.showMessageDialog(new JFrame(),"修改成功","成功",JOptionPane.WARNING_MESSAGE);
getTable();
}else{
JOptionPane.showMessageDialog(new JFrame(),"此人不存在","警告",JOptionPane.WARNING_MESSAGE);
}
}catch(SQLException exc){
exc.printStackTrace();
}finally{
if(ps!=null)try{ps.close();}catch(SQLException ignore){}
if(dbConn!=null)try{dbConn.close();}catch(SQLException ignore){}
}
}
}
});
exit_button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
}
});
add_button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String[] temp={"",""};
temp[0]=studentno_textfield.getText();
temp[1]=studentname_textfield.getText();
if(temp[0].equals("")&&temp[1].equals("")){
JOptionPane.showMessageDialog(new JFrame(),"空值,不合法","警告",JOptionPane.WARNING_MESSAGE);
}else if(temp[0].length()!=11){
JOptionPane.showMessageDialog(new JFrame(),"学号,不合法","警告",JOptionPane.WARNING_MESSAGE);
}else{
try{
dbConn=DriverManager.getConnection(dbURL,username,password);
String addStr="insert into student (sno,sname) values(?,?)";
String selectStr="select * from student where sno=?";
ps=dbConn.prepareStatement(selectStr);
ps.setString(1,studentno_textfield.getText());
rs=ps.executeQuery();
if(!rs.next()){
ps=dbConn.prepareStatement(addStr);
ps.setString(1,studentno_textfield.getText());
ps.setString(2,studentname_textfield.getText());
ps.executeUpdate();
JOptionPane.showMessageDialog(new JFrame(),"添加成功","成功",JOptionPane.WARNING_MESSAGE);
getTable();
}else{
JOptionPane.showMessageDialog(new JFrame(),"学号已存在","警告",JOptionPane.WARNING_MESSAGE);
}
}catch(SQLException exc){
exc.printStackTrace();
}finally{
if(ps!=null)try{ps.close();}catch(SQLException ignore){}
if(dbConn!=null)try{dbConn.close();}catch(SQLException ignore){}
}
}
getTable();
}
});
delete_button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String[] temp={"",""};
temp[0]=studentno_textfield.getText();
temp[1]=studentname_textfield.getText();
if(temp[0].equals("")&&temp[1].equals("")){
JOptionPane.showMessageDialog(new JFrame(),"空值,不合法","警告",JOptionPane.WARNING_MESSAGE);
}else if(!(temp[0].equals(""))&&temp[0].length()!=11){
JOptionPane.showMessageDialog(new JFrame(),"学号,不合法","警告",JOptionPane.WARNING_MESSAGE);
}else{
try{
dbConn=DriverManager.getConnection(dbURL,username,password);
String deleteStr="delete from student WHERE sno=? or sname=?";
String selectStr="select * from student where sno=? or sname=?";
ps=dbConn.prepareStatement(selectStr);
ps.setString(1,studentno_textfield.getText());
ps.setString(2,studentname_textfield.getText());
rs=ps.executeQuery();
if(rs.next()){
ps=dbConn.prepareStatement(deleteStr);
ps.setString(1,studentno_textfield.getText());
ps.setString(2,studentname_textfield.getText());
ps.executeUpdate();
JOptionPane.showMessageDialog(new JFrame(),"修改成功","成功",JOptionPane.WARNING_MESSAGE);
getTable();
}else{
JOptionPane.showMessageDialog(new JFrame(),"此人不存在","警告",JOptionPane.WARNING_MESSAGE);
}
}catch(SQLException exc){
exc.printStackTrace();
}finally{
if(ps!=null)try{ps.close();}catch(SQLException ignore){}
if(dbConn!=null)try{dbConn.close();}catch(SQLException ignore){}
}
}
getTable();
}
});
table = new JTable();
Container c = getContentPane();
c.setLayout( new BorderLayout() );
//将"topPanel"编辑框布置到 "NORTH"
c.add( topPanel, BorderLayout.NORTH );
//将"table"编辑框布置到 "CENTER"
c.add( table, BorderLayout.CENTER );
getTable();
setSize( 500, 300 );
//显示Frame
show();
Toolkit kit=Toolkit.getDefaultToolkit();
Dimension screenSize=kit.getScreenSize();
int width=screenSize.width;
int height=screenSize.height;
setLocation((width-getWidth())/2,(height-getHeight())/2);
}
private void getTable()
{
try{
//执行SQL语句
String query ="SELECT sno as '学号',sname as '姓名' FROM student";
ps=dbConn.prepareStatement(query);
rs=ps.executeQuery();
//在表格中显示查询结果
displayResultSet(rs);
}catch(SQLException sqlex){
sqlex.printStackTrace();
}
}
private void displayResultSet(ResultSet rs)throws SQLException{
//定位到达第一条记录
boolean moreRecords = rs.next();
//如果没有记录,则提示一条消息
if (! moreRecords){
JOptionPane.showMessageDialog( this,"结果集中无记录" );
setTitle( "无记录显示" );
return;
}
Vector columnHeads = new Vector();
Vector rows = new Vector();
try{
//获取字段的名称
ResultSetMetaData rsmd = rs.getMetaData();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );
//获取记录集
do{
rows.addElement( getNextRow( rs, rsmd ) );
}while(rs.next());
//在表格中显示查询结果
table = new JTable( rows, columnHeads );
JScrollPane scroller = new JScrollPane( table );
c.remove(1);
c.add( scroller, BorderLayout.CENTER );
//刷新Table
c.validate();
}catch(SQLException sqlex){
sqlex.printStackTrace();
}
}
private Vector getNextRow(ResultSet rs,ResultSetMetaData rsmd)throws SQLException{
Vector currentRow = new Vector();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
currentRow.addElement( rs.getString( i ) );
//返回一条记录
return currentRow;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -