import java.awt.*;import java.awt.event.*;import java.sql.*;import java.util.*;import javax.swing.*;import UI.StudentUI; class AddStudentFrame extends JFrame{ private StudentUI userInterface; private JButton clearButton,writeButton; static final String JDBC_DRIVER="sun.jdbc.odbc.JdbcOdbcDriver"; static final String DATABASE_URL="jdbc:odbc:studyDSN"; private Connection connection; private Statement statement; String sqlString; String names[]={"学号","姓名","性别","年龄","所在系" }; public AddStudentFrame(){ super("add a record of students"); initialize(); userInterface=new StudentUI(names); getContentPane().add(userInterface,BorderLayout.CENTER); writeButton=userInterface.getDotask1Button(); writeButton.setText("保存"); writeButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ addRecord(); } }); clearButton=userInterface.getDoTask2Button(); clearButton.setText("清除"); clearButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent event){ userInterface.clearFields(); } }); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent event) { terminate(); } }); setSize(300,200); setVisible(true); } public void initialize() { try{ Class.forName(JDBC_DRIVER); connection=DriverManager.getConnection(DATABASE_URL,"sa",null); statement=connection.createStatement(); } catch(SQLException sqlException){ JOptionPane.showMessageDialog(null,sqlException.getMessage(),"Database error",JOptionPane.ERROR_MESSAGE); System.exit(1); } catch(ClassNotFoundException classNotFound){ JOptionPane.showMessageDialog(null,classNotFound.getMessage(),"driver not found",JOptionPane.ERROR_MESSAGE); System.exit(1); } } public void terminate(){ try{ statement.close(); connection.close(); } catch(SQLException sqlException){ JOptionPane.showMessageDialog(null,sqlException.getMessage(),"database error",JOptionPane.ERROR_MESSAGE); System.exit(1); } } public void addRecord(){ String fieldValues[]=userInterface.getFieldValues(); if(!fieldValues[StudentUI.SNO].equals("")){ try{ int numberAge=Integer.parseInt(fieldValues[StudentUI.SAGE]); String sqlInsert="insert into student"+"values('"+fieldValues[0]+"','"+fieldValues[1]+"','"+fieldValues[2]+"',"+numberAge+",'"+fieldValues[4]+"')"; int result=statement.executeUpdate(sqlInsert); if(result!=0){ userInterface.clearFields(); JOptionPane.showMessageDialog(this,"inserted sucess!","insert result",JOptionPane.INFORMATION_MESSAGE); } } catch(NumberFormatException formatException){ JOptionPane.showMessageDialog(this,"bad age numver","invalid numver format",JOptionPane.ERROR_MESSAGE); } catch(SQLException ee) {System.out.println(ee); } } else JOptionPane.showMessageDialog(this,"bad sno number","invalid number format",JOptionPane.ERROR_MESSAGE); } public static void main(String args[]){ new AddStudentFrame(); }}

评论