实验8-学生管理系统-数据库应用开发

一 实验内容

本实验要求学生使用JDBC提供的接口和类编写一个Java应用程序,实现对学生数据信息的查询、删除、插入、更新等操作。

学生数据库(student)在MySQL数据库服务器中创建。

1. 在MySQL中创建学生数据库student,其中一个学生信息表stuinfo结构如下:

                         图1  stuinfo表结构

2. 设计一个Java程序,界面如图2所示,实现以下功能:

(1)点击“全部检索”按钮,检索stuinfo表的所有记录,显示在上面的JTable组件中;

(2)输入查询学号,点击“查询”按钮,查询该学生信息显示在左边面板中,查询不到时弹出信息提示。

(3)左边面板中输入学生信息,点击“添加”按钮,将此学生信息插入stuinfo表中,弹出插入是否成功的提示框。

(4)点击“删除”按钮,依据上边学号值删除该学生记录,弹出删除是否成功的提示框。

(5)点击“更新”按钮,依据上边学号值更新该学生的其它信息,弹出更新是否成功的提示框。

*首先完成界面设计,然后逐项功能实现,可以选作部分功能。

                                            图2  学生数据管理

二 实验思路

    1,画界面,
    2,连接数据库
    3,对数据库操作

三 画界面

四 连接数据库

package studentsql;

import java.sql.*;

public class Test_connect_SQL {
    
    public static void main(String[] args) {
        String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        String dbURL = "jdbc:sqlserver://localhost:1433;DatabaseName=student";
        String userName = "lw";
        String userPwd = "123456";
        try {
            Class.forName(driverName);
            System.out.println("加载驱动成功!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("加载驱动失败!");
        }
        try {
            Connection dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
            System.out.println("连接数据库成功!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("SQL Server连接失败!");
        }
        ///new StudentJFrame(new StudentJPanel(),"studentim");
    }
}

五 对数据库操作

-------------------------------------

六 程序代码

链接:http://pan.baidu.com/s/1eR97AkM 密码:otun

StudentJFrame

package studentsql;
/*
 * 思路:1,画界面,
 *        2,连接数据库
 *         3,对数据库操作
 * */
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;                                             
public class StudentJFrame extends JFrame implements ActionListener, ListSelectionListener {//响应按钮动作和列表框选择事件
    protected StudentJPanel student;     // Student对象信息面板
    protected JTable jtable;            //表格
    public JButton inquire, allsearch;    //查询,全部检索按钮
    public JTextField number;            //学号
    JPanel rightpanel;                    //左边的StudentJPanel面板
    private JScrollPane scrollPane;        //滚动窗格
    public Connection conn;             //数据库连接对象
    String userName = "lw";                //数据库名字
    String userPwd = "123456";            //数据库密码
    /**
     * 整体的框架,
     * @param StudentJFrame 
     * */
    public StudentJFrame(StudentJPanel person, String driver, String url) throws ClassNotFoundException, SQLException {
        super("Student对象信息管理");                        //标题
        this.setSize(800, 300);                         // 设置组件尺寸
        this.setLocationRelativeTo(null);                 // 将窗口置于屏幕中央
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.student = person;                             // Person对象或其子类信息面板
        rightpanel = new JPanel(new BorderLayout());    // 面板边布局
        JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, this.student, rightpanel);
                                                        // 水平分割窗格,左右边各添加一个面板
        split.setDividerLocation(200);                     // 设置水平分隔条的位置
        this.getContentPane().add(split);                 // 框架内容窗格添加分割窗格
        Class.forName(driver);
        this.conn = DriverManager.getConnection(url, this.userName, this.userPwd); // 返回数据库连接对象
        jtable=new JTable();
        scrollPane = new JScrollPane(jtable);// 面板添加包含列表框的滚动窗格
        rightpanel.add(scrollPane,"Center");
        JPanel buttonpanel = new JPanel(); // 按钮面板,默认流布局
        rightpanel.add(buttonpanel, "South"); // 南边添加按钮面板

        buttonpanel.add(new Label("学号"));
        number=new JTextField("102012012", 10);
        buttonpanel.add(number);
        inquire=new JButton("查询");
        buttonpanel.add(inquire);
        this.inquire.addActionListener(this);
        this.allsearch = new JButton("全部检索");
        buttonpanel.add(this.allsearch);
        this.allsearch.addActionListener(this);
        this.setVisible(true);
    }
    /**
     * 获得表格模型
     * @param 
     * */
    public DefaultTableModel query(String table) throws SQLException {
        DefaultTableModel tablemodel = new DefaultTableModel();     // 表格模型
        String sql = "SELECT * FROM " + table + ";";
        Statement stmt = this.conn.createStatement();                // 1003,1007); //创建语句对象
        ResultSet rset = stmt.executeQuery(sql);                     // 执行数据查询SELECT语句
        // 获得表中列数及各列名,作为表格组件的标题
        ResultSetMetaData rsmd = rset.getMetaData();                 // 返回表属性对象
        int count = rsmd.getColumnCount();                             // 获得列数
        for (int j = 1; j <= count; j++)                             // 将各列名添加到表格模型作为标题,列序号≥1
            tablemodel.addColumn(rsmd.getColumnLabel(j));
        // 将结果集中各行数据添加到表格模型,一次遍历
        Object[] columns = new Object[count];                         // 创建列对象数组,数组长度为列数
        while (rset.next())                                         // 迭代遍历结果集,从前向后访问每行
        {
            for (int j = 1; j <= columns.length; j++)                 // 获得每行各列值
                columns[j - 1] = rset.getString(j);
            tablemodel.addRow(columns);                             // 表格模型添加一行,参数指数各列值

        }
        rset.close();
        stmt.close();
        return tablemodel;                                             // 创建表格,指定表格模型

    }

    @Override
    public void valueChanged(ListSelectionEvent arg0) {
        // TODO Auto-generated method stub

    }
/**
 * 查询,全部检索,按钮触发事件
 * @param
 * */
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == allsearch) {
            System.out.println(99);
            try {
                
                jtable.setModel(query("studentim"));

            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        if(e.getSource()==inquire)
        {
            try {
                String num = "112";
                String sql="SELECT* from studentim where stu_id='"+num+"'";
                Statement stmt = this.conn.createStatement();// 1003,1007); //创建语句对象
                ResultSet rset = stmt.executeQuery(sql); // 执行数据查询SELECT语句
//                ResultSetMetaData rsmd=rset.getMetaData();
//                int count=rsmd.getColumnCount();
//                String result1 = null;
//                String result2 = null;
//                String result3 = null;
//                
//                while(rset.next())
//                {    String result[] = new String[6];                        
//                         result1 = rset.getString(1);
//                         result2 = rset.getString(2);
//                         result3 = rset.getString(3);
//                        
//                }
//                //this.number.setText(re);
//                new StudentJPanel().setString("1", "22", "33");
                
                rset.next();
                student.texts[0].setText(rset.getString(1));
            } catch (SQLException e1) {
            
                e1.printStackTrace();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

    }
    
    public static void main(String arg[]) throws ClassNotFoundException, SQLException {

        String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; // 指定MySQL// JDBC驱动程序
        String url = "jdbc:sqlserver://localhost:1433;DatabaseName=student";
        new StudentJFrame(new StudentJPanel(), driver, url);
    }

}

StudentJPanel

package studentsql;

import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.*;
import javax.swing.border.TitledBorder;
/**
 * studentJPanel 面板  
 * @param 
 * */
public class StudentJPanel extends JPanel implements ActionListener// ,ItemListener
                                                                    // //Person对象信息面板
{
    JTextField texts[];                             // 文本行数组,表示学号,姓名、出生日期
    JRadioButton radiobs[];                         // 性别按钮
    JTextField combox_province, combox_city;         // 省份、城市组合框
    JButton add, delete, update;                    //添加 删除 更新按钮
    Connection conn;                                 // 数据库连接对象
    String userName = "lw";                             //用户名
    String userPwd = "123456";                        //密码
    String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";             // 指定MySQL//
    String url = "jdbc:sqlserver://localhost:1433;DatabaseName=student";
    /**
     * 学生信息面板
     * */
    public StudentJPanel() throws ClassNotFoundException, SQLException            // 构造方法
    {
        Class.forName(this.driver);                                                //指定JDBC驱动程序
        this.conn = DriverManager.getConnection(url, this.userName, this.userPwd);//创建接口的连接对象
        this.setBorder(new TitledBorder("Student"));                             // 设置面板具有带标题的边框
        this.setLayout(new GridLayout(7, 1));                                     // 面板网格布局,行1列
        String str[][] = { { "学号","姓名", "1990年01月01日" }, { "男", "女" } };        //信息数组
        this.texts = new JTextField[str[0].length];
        for (int i = 0; i < this.texts.length; i++)                             // 面板添加两个文本行
            this.add(this.texts[i] = new JTextField(str[0][i]));
        JPanel panel_rb = new JPanel(new GridLayout(1, 2));                         // 性别面板,网格布局,1行2列,单选按钮
        this.add(panel_rb);
        ButtonGroup bgroup = new ButtonGroup();                                 // 按钮组
        this.radiobs = new JRadioButton[str[1].length];
        for (int i = 0; i < this.radiobs.length; i++) {
            panel_rb.add(this.radiobs[i] = new JRadioButton(str[1][i]));         // 创建单选按钮,默认不选中,添加到面板
            bgroup.add(this.radiobs[i]);                                         // 单选按钮添加到按钮组
        }
        this.radiobs[0].setSelected(true);                                         // 单选按钮选中
        this.add(this.combox_province = new JTextField("广东"));                    // 省份组合框
        this.add(this.combox_city = new JTextField("广州"));                        // 城市组合框
        this.combox_province.addActionListener(this);                             // 省份组合框注册单击事件监听器
        JPanel panel_bu = new JPanel(new GridLayout(1, 3));
        this.add(panel_bu);
        panel_bu.add(this.add = new JButton("添加"));                                //添加按钮
        this.add.addActionListener(this);                                        
        panel_bu.add(this.delete = new JButton("删除"));                            //删除按钮
        this.delete.addActionListener(this);
        panel_bu.add(this.update = new JButton("更新"));                            //更新按钮
        this.update.addActionListener(this);
    }
    /**
     * 添加  删除 更新按钮的触发事件
     * */    
    @Override
    public void actionPerformed(ActionEvent ex) {
        /**
         * 获得觉得输入的信息
         * */
        String numbers=texts[0].getText();
        String names=texts[1].getText();
        String brithday=texts[2].getText();
        String sex=radiobs[0].isSelected()?radiobs[0].getText():radiobs[1].getText();
        String prirvince=combox_province.getText();
        String city=combox_city.getText();
        if (ex.getSource() == this.add) {                //添加动作
            String sql = "INSERT INTO studentim(stu_id,stu_name,birthday,sex,province,city)" + "VALUES('"+numbers+"','"+names+"','"+brithday+"','"+sex+"','"+prirvince+"','"+city+"')";
            try {
                Statement stmt = this.conn.createStatement();
                int count = stmt.executeUpdate(sql);
            } catch (SQLException e) {
                e.printStackTrace();
            }                         // 1003,1007); //创建语句对象

            System.out.println(2);
            JOptionPane.showMessageDialog(this, "添加成功");
        }
        if (ex.getSource() == this.delete) {             //删除动作    
            String sql = "DELETE FROM studentim WHERE(stu_id='"+numbers+"')";
            try {
                Statement stmt = this.conn.createStatement();
                int count = stmt.executeUpdate(sql);
            } catch (SQLException e) {
                e.printStackTrace();
            } // 1003,1007); //创建语句对象

            System.out.println(4);
            JOptionPane.showMessageDialog(this, "删除成功");
        }
        if (ex.getSource() == this.update) {        //更新动作
            String sql = "update studentim set stu_name='"+names+"' where (stu_id='"+numbers+"')";
            try {
                Statement stmt = this.conn.createStatement();
                int count = stmt.executeUpdate(sql);
            } catch (SQLException e) {
                e.printStackTrace();
            }                     // 1003,1007); //创建语句对象

            System.out.println(3);
            JOptionPane.showMessageDialog(this, "更新成功");
        }

    }

}

 

 

posted @ 2016-11-30 17:13  8亩田  阅读(2002)  评论(0编辑  收藏  举报