Java连接数据库作业

一、学生信息管理系统

建立数据库mytest和数据表student,利用JTabbedPane新建选项卡,一个名为“inputPanel”(录入记录)。另一个名为“viewPanel”(浏览记录)。

表结构如下:

录入记录界面效果:  

浏览记录界面效果:

运行结果如下:🙁😓😶🤨😐😮😞🙃🙄🐷😕 

代码如下:

public class StudentManager extends JFrame {
    JTabbedPane tabbedPane=new JTabbedPane();
    JButton inputBtn,viewBtn;
    JTextField noField,nameField,gendarField,telField;
    JTextArea viewArea;
    JLabel noLabel,nameLabel,gendarLabel,telLabel;
    JPanel inputPanel,viewPanel,panel1,panel2;
    Connection conn;
    Statement stmt;
    InputAction inputAction=new InputAction();
    ViewAction viewAction=new ViewAction();
    public StudentManager() {
        setTitle("学生信息管理系统");
        setBounds(0,0,500,344);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//        this.setResizable(false);
        init();
        
    }
    private void init() {
        noLabel=new JLabel("学号");
        nameLabel=new JLabel("姓名");
        gendarLabel=new JLabel("性别");
        telLabel=new JLabel("联系电话");
        noField=new JTextField(9);
        nameField=new JTextField(9);
        gendarField=new JTextField(9);
        telField=new JTextField(9);
        inputBtn=new JButton("录入");
        viewBtn=new JButton("浏览");
        viewArea=new JTextArea(10,20);
        panel1=new JPanel();
        panel1.setLayout(null);
        panel2=new JPanel();
        panel2.setLayout(null);
        panel1.add(noLabel);
        panel1.add(noField);
        panel1.add(nameLabel);
        panel1.add(nameField);
        panel1.add(gendarLabel);
        panel1.add(gendarField);
        panel1.add(telLabel);
        panel1.add(telField);
        panel1.add(inputBtn);
        
        noLabel.setBounds(40,26,30,23);
        noField.setBounds(90,26,120,23);
        nameLabel.setBounds(260,26,30,23);
        nameField.setBounds(310,26,120,23);
        gendarLabel.setBounds(40,100,30,23);
        gendarField.setBounds(90,100,120,23);
        telLabel.setBounds(235,100,60,23);
        telField.setBounds(310,100,120,23);
        inputBtn.setBounds(205,180,65,25);
        
        panel2.add(viewArea);
        panel2.add(viewBtn);
        viewArea.setBounds(31,31,420,150);
        viewBtn.setBounds(205,200,65,25);
        
        inputBtn.addActionListener(inputAction);
        viewBtn.addActionListener(viewAction);
        tabbedPane.addTab("录入记录",panel1);
        tabbedPane.addTab("浏览记录",panel2);
        this.add(tabbedPane);
    }
    private void connection() {
        try {
             Class.forName ("com.mysql.jdbc.Driver")   ;  //装载MySQL驱动程序;
             conn = DriverManager.getConnection  ("jdbc:mysql://127.0.0.1:3306/mytest?characterEncoding=utf8&useSSL=false","root","r")  ;   //连接MySQL数据库mytest
             stmt = conn.createStatement();    //获得执行语句对象stmt;
                } catch (ClassNotFoundException e1) {
                    System.err.println("驱动程序装载失败!");
                } catch (SQLException e2) {
                    e2.getSQLState();
                    e2.getMessage();
                }
    }
    private void close() {
         try {
                if (stmt != null) {
                    stmt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e2) {
                System.err.println("不能正常关闭");
            }
    }
    
    class InputAction implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            String sno = noField.getText();   //获得学号
               String sname = nameField.getText();   //获得姓名
               String sgendar = gendarField.getText();   //获得性别
               String stel = telField.getText();    //获得联系电话;
               try {
                   connection();
                   String InsSQL;
                   InsSQL = "INSERT INTO student (no,name,gendar,tel)" + "VALUES(" + "'" + sno + "'," + "'" + sname + "'," + "'" + sgendar + "'," + "'" + stel +"')";  //定制插入SQL语句字符串
                   int rs = stmt.executeUpdate(InsSQL);   //执行将新记录插入到数据表student中
                   JOptionPane.showMessageDialog(null, "记录已添加!");
                  } catch (SQLException e1) {
                      System.err.println(e1.getSQLState());
                  } finally {
                       close();    //关闭数据库
                      }
        }
    }
    class ViewAction implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            try {
                String viewString = "";
                connection();
                ResultSet rs = stmt.executeQuery("SELECT * From student");
                ResultSetMetaData rsMeta = rs.getMetaData();
                 int nums = rsMeta.getColumnCount();
                 //获得字段名称;
                 for (int i = 1; i <= nums; i++) {
                      viewString += rsMeta.getColumnName(i) + "\t";
                 }
                 viewString += "\n";
                 //获得数据表student的记录;
                 while (rs.next()) {
                    for (int i = 1; i <= nums; i++) {
                         viewString += rs.getString(i) + "\t";
                    }
                    viewString += "\n";
                    viewArea.setText(viewString);
                  }
                } catch (SQLException e1) {
                     System.err.println("浏览学生记录失败");
                       System.err.println(e1.getSQLState() + e1.getMessage());
                   } finally {
                       close();
                    }
        }
    }
    
    
    public static void main(String[] args) {
        new StudentManager().setVisible(true);
    }

}

开始时选项卡当面板来添加了,所以只能显示一个面板。添加方式是tabbedPane.addTab()。

布局花了n久n久的时间。。。自闭了。。。

没用过Box,只用过Flow和Grid,这回用了个空布局来手动设置坐标和长度,作为一个强迫症,wkiao我真的是。。。


 

二、目录树

使用的是access驱动。

运行结果如下:

代码如下:

 

public class ShowTree
{
    public static void main(String[] args) 
    {
         Tree_View myTree;
         myTree=new Tree_View();
    }
}


class Tree_View extends JFrame 
{
//odbc驱动
//      String DBDriver="sun.jdbc.odbc.JdbcOdbcDriver";
//access驱动
      String DBDriver="com.hxtt.sql.access.AccessDriver";
//odbc连接
//      String connectionStr="jdbc:odbc:CKconn";   
//jdbc直连
      String connectionStr="jdbc:access:////C://Java程序设计//目录树//ck.mdb";
      Connection con = null;
      Statement stmt = null;
      ResultSet rs = null;
      JTree myTree;

      public Tree_View()
      {super("目录树演示");
       setSize( 500, 500 ); 
       if (linkDatabase())
         createTree();    
       setVisible(true);
       addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e) {
                                closeDatabase();
                            }
                         } 
                       );  
      }

      public boolean linkDatabase()  
      {
       try{
           Class.forName(DBDriver);     //加载驱动器
           con=DriverManager.getConnection(connectionStr,"","");
       stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);   //创建Statement对象
          }
       //捕获加载驱动程序异常
       catch ( ClassNotFoundException cnfex )
          { 
           System.err.println("装载 JDBC/ODBC 驱动程序失败。" ); 
       return(false);
          } 
      //捕获连接数据库异常
      catch ( SQLException sqlex ) 
         { 
           System.err.println( "无法连接数据库" ); 
       return(false);
         } 
      return(true);
      }

  
    public void createTree()
    {
       DefaultMutableTreeNode[] aNode=new DefaultMutableTreeNode[7];
       String curHH="",curMC;
       int dotCount=0;
    try{
        rs=stmt.executeQuery("select * from clggb order by hh");  //查询表
      while(rs.next())         //显示所有记录
      {
           curHH=rs.getString("hh").trim();
           curMC=rs.getString("mc").trim();
           dotCount=curHH.length()/2;
           System.out.println(dotCount+"="+curHH+":"+curMC+"\n");
           if (dotCount==0)
             aNode[0]=new DefaultMutableTreeNode(curHH+":"+curMC);
           else
             {
              aNode[dotCount]=new DefaultMutableTreeNode(curHH+":"+curMC);
              aNode[dotCount-1].add(aNode[dotCount]);
             }

      };
      }
    catch(Exception e)
      {
         System.err.println( "数据库出错" ); 
         System.exit( 1 );  // terminate program 
     }
    Container c = getContentPane(); 
    myTree = new JTree(aNode[0]);
    c.add(new JScrollPane(myTree));
//    MyDefaultTreeCellRenderer x = new MyDefaultTreeCellRenderer();
//    tree.setCellRenderer(x)       //用于设置结点图标
   }

    public void closeDatabase() 
     {
     try{
        if (stmt!=null)stmt.close();  //关闭语句
        if (con!=null) con.close();   //关闭连接
       }
     catch(Exception e)
       {
         System.err.println( "数据库出错" ); 
         System.exit( 1 );  // terminate program 
       }
    }
}

 

啊为什么作业这么多🙃啊我自闭了🙃啊我还要好多课要预习啊啊啊😭

 

posted @ 2019-06-10 23:46  流离丶  阅读(880)  评论(0编辑  收藏  举报