zzuli 实验三 数据库编程

三、实验任务

编程管理学生数据。要求:

1. 自选数据库管理系统创建数据库stu,按照下表的结构创建"student"表:

字段名

Java数据类型

宽度

SQL数据类型

id

int

10

int

Name

String

20

Char(20)

Sex

String

2

Char(2)

Age

Int

3

Integer

假设表中已有3个学生的数据:

id

Name

Sex

Age

1

张小明

18

2

李雷

19

3

韩梅梅

18

2. 设计图形用户界面,通过事件处理实现学生数据管理功能。

3. 用恰当的方法处理可能出现的异常。

4. 将数据表stu及其数据操作封装成类,将数据操作功能封装成类的方法,通过该类,借助图形用户界面实现下面功能:

(1)向表中增加记录并显示增加后的所有记录(新增记录的具体数据自定);

(2)从表中删除id=1的记录,并显示删除后的所有记录;

(3)修改表中记录:查询条件id=2,将name修改为:王杰,修改完毕显示所有记录;

(4)查询表中id=3的记录并显示。

四、实验要求

1. 程序要添加适当的注释,程序的书写要采用缩进格式

2. 程序要具备一定的健壮性,即当输入数据非法时,程序也能适当地做出反应,如插入删除时指定的位置不对等等。

3. 程序要做到界面友好,在程序运行时用户可以根据相应的提示信息进行操作。

首先:连接数据库的时候数据库名称要改一下比如我的数据库名称:yang

String url = "jdbc:mysql://127.0.0.1:3306/yang?useSSL=false";

用户名一般是:root(根用户)

密码:自己设置的MySQL密码

一.Main

package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    public static void main(String[] args) {
        createDatabase();
        createTable_insert();
        new interfaceJFrame();
    }
    //创建数据库
    private static void createDatabase() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("加载驱动成功");
        } catch (Exception e) {
            System.out.println("加载驱动失败");
            System.out.println(e);
        }
        Connection con;
        String url = "jdbc:mysql://127.0.0.1:3306/yang?useSSL=false";
        String user = "root";
        String password = "123456";
        try {
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("成功连接到数据库");
            }
            Statement statement = con.createStatement();
            String sql = "create database stu";
            int rs = statement.executeUpdate(sql);
            if (rs != 0) {
                System.out.println("成功创建数据库");
            } else {
                System.out.println("创建数据库失败");
            }

            statement.close();
            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
//创建表并插入数据
    private static void createTable_insert() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("加载驱动成功");
        } catch (Exception e) {
            System.out.println("加载驱动失败");
            System.out.println(e);
        }
        Connection con;
        String url = "jdbc:mysql://127.0.0.1:3306/yang?useSSL=false";
        String user = "root";
        String password = "123456";
        try {
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("成功连接到数据库");
            }
            Statement statement = con.createStatement();
            String sql1="use stu";
            try {
                statement.executeUpdate(sql1);
                System.out.println("正在使用stu数据库");
            } catch (SQLException e) {
                System.out.println("切换数据库失败");
                e.printStackTrace();
            }
            String sql3 = "create table student(" +
                    "id int," +
                    "Name char(20)," +
                    "Sex char(2)," +
                    "Age integer)";
            int rs3 = statement.executeUpdate(sql3);
            if (rs3 == 0) {
                System.out.println("成功创建学生表");
            } else {
                System.out.println("创建学生表失败");
            }
            String sql4="insert into student " +
                    "values(1,'张小明','男',18)," +
                    "(2,'李雷','男',19)," +
                    "(3,'韩梅梅','女',18)";
            int rs4= statement.executeUpdate(sql4);
            if(rs4!=0)
                System.out.println("插入数据成功");
            else
                System.out.println("插入数据失败");
            statement.close();
            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

二. interfaceJFrame

package database;


import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.ArrayList;

public class interfaceJFrame extends JFrame {
    public static JTable jTable;
    public static DefaultTableModel model;

    public interfaceJFrame() {
        //初始化界面
        initJFram();
        //设置菜单栏
        initJMenubar();
        //显示表格
        table();
        this.setVisible(true);
    }

    public void table() {
        Connection con = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("加载驱动成功");
        } catch (Exception e) {
            System.out.println("加载驱动失败");
            System.out.println(e);
        }
        String url = "jdbc:mysql://127.0.0.1:3306/yang?useSSL=false";
        String user = "root";
        String password = "123456";
        try {
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("成功连接到数据库");
            }
            statement = con.createStatement();
            String sql1 = "use stu";
            try {
                statement.executeUpdate(sql1);
                System.out.println("正在使用stu数据库");
            } catch (SQLException e) {
                System.out.println("切换数据库失败");
                e.printStackTrace();
            }
            // 查询student表中的所有数据
            String sql = "SELECT * FROM student";
            resultSet = statement.executeQuery(sql);
            if (resultSet != null && resultSet.next()) {
                System.out.println("查询成功!");
                //创建一个二维数组,用于存放查询出来的数据
                Object[][] tables ;
                //创建集合,ArrayList<Object[]>中Object[]表示集合中存放的数据类型
                ArrayList<Object[]> list = new ArrayList<>();
                do {
                    int id = resultSet.getInt("id");
                    String age = resultSet.getString("Name");
                    String gender = resultSet.getString("Sex");
                    int Age = resultSet.getInt("Age");
                    //向集合里面增加数据
                    list.add(new Object[] {id, age, gender, Age});
                } while (resultSet.next());
                //toArray(new Object[0][]) 方法则是将 List 中的元素转换为一个二维 Object 数组
                tables=list.toArray(new Object[0][]);
                // 创建一个JTable并将其添加到JScrollPane中
                String tableTitle[] = {"id", "Name", "Sex", "Age"};
                model = new DefaultTableModel(tables, tableTitle);
                jTable = new JTable(model);
                JScrollPane scroll = new JScrollPane(jTable);
                this.add(scroll);
            } else {
                System.out.println("查询结果为空!");
            }

        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (SQLException e) {
                System.out.println(e);
            }
        }
    }

    private void initJMenubar() {
        //创建菜单对象JMenuBar
        JMenuBar jMenuBar = new JMenuBar();
        //创建(功能,帮助)选项JMenu
        JMenu jMenufunction = new JMenu("功能");
        JMenu jMenuabout = new JMenu("帮助");
        //创建(增、删、改、查)的功能JMenuItem
        JMenuItem jMenuItem1 = new JMenuItem("增加学生信息");
        JMenuItem jMenuItem2 = new JMenuItem("删除学生信息");
        JMenuItem jMenuItem3 = new JMenuItem("修改学生信息");
        JMenuItem jMenuItem4 = new JMenuItem("查询学生信息");
        //将菜单栏中的四个功能加到功能选项中去
        jMenufunction.add(jMenuItem1);
        jMenufunction.add(jMenuItem2);
        jMenufunction.add(jMenuItem3);
        jMenufunction.add(jMenuItem4);
        //将菜单中的两个选项加到菜单栏
        jMenuBar.add(jMenufunction);
        jMenuBar.add(jMenuabout);
        //给四个功能设置事件(监听),调用不同的方法
        jMenuItem1.setActionCommand("add_student_info");

        jMenuItem1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String command = e.getActionCommand();
                if ("add_student_info".equals(command)) {
                    new add();
                }
            }
        });
        jMenuItem2.setActionCommand("delete_student_info");
        jMenuItem2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String command = e.getActionCommand();
                if ("delete_student_info".equals(command)) {
                    new delete();
                }
            }
        });
        jMenuItem3.setActionCommand("update_student_info");
        jMenuItem3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String command = e.getActionCommand();
                if ("update_student_info".equals(command)) {
                    new update();
                }
            }
        });
        jMenuItem4.setActionCommand("select_student_info");
        jMenuItem4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String command = e.getActionCommand();
                if ("select_student_info".equals(command)) {
                    //new select();
                }
            }
        });
        //给整个窗口设置菜单
        this.setJMenuBar(jMenuBar);
    }

    private void initJFram() {
        //设置界面的宽高
        this.setSize(800, 600);
        //设置标题的题目
        this.setTitle("学生管理系统");
        //设置默认的关闭方式
        this.setDefaultCloseOperation(3);
        //取消默认的居中放置,这样才能在窗口中按照X-Y轴放置
        //this.setLayout(null);
        //设置界面居中
        this.setLocationRelativeTo(null);
    }
}

三.add

package database;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class add extends JFrame{
    JButton jButton;
    public add() {
        //初始化界面
        jienmian();
        //创建一个文本框
        textArea();
        //增加按钮
        sureButton();
        this.setVisible(true);
    }
    
private void textArea() {
    // 创建一个文本框
    JTextField jTextField = new JTextField("请输入增加的学生信息,中间以空格隔开,完成后回车",20);
    jTextField.setBounds(100,100,300,30);
    this.add(jTextField);

    // 为文本框添加 ActionListener 监听器
    jTextField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String text = jTextField.getText();
            //将获取到的字符串进行分割,通过空格
            String[] addtext=text.split("\\s");
            //获取到创建的模型添加数据
            adduser(addtext);
            //执行sql语句,插入到数据库
            execute_sql(addtext);
        }
    });
    // 将文本框添加到窗口中
    this.add(jTextField);
}
    private void sureButton() {
        jButton = new JButton("确定");
        jButton.setBounds(240, 200, 60, 20);
        //这里用匿名内部类实现接口ActionListener
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(add.super.rootPane, "增加信息成功");
            }
        });
        //将按钮增加到面板
        this.getContentPane().add(jButton);
    }
    public void adduser(Object[] a){

        interfaceJFrame.model.addRow(a);
    }

    private void jienmian() {
        this.setSize(500, 300);
        this.setTitle("增加学生信息");
        //设置页面置顶
        this.setAlwaysOnTop(true);
        this.setLocationRelativeTo(null);
        //取消默认的居中放置,在这里我们需要添加按钮,需要设置按钮位置
        this.setLayout(null);
        this.setDefaultCloseOperation(2);
    }
    public void execute_sql(Object[] objects){
        Connection con = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("加载驱动成功");
        } catch (Exception e) {
            System.out.println("加载驱动失败");
            System.out.println(e);
        }
        String url = "jdbc:mysql://127.0.0.1:3306/yang?useSSL=false";
        String user = "root";
        String password = "123456";
        try {
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("成功连接到数据库");
            }
            statement = con.createStatement();
            String sql1 = "use stu";
            try {
                statement.executeUpdate(sql1);
                System.out.println("正在使用stu数据库");
            } catch (SQLException e) {
                System.out.println("切换数据库失败");
                e.printStackTrace();
            }
            // 增加student表中的数据
//            String sql = "insert into Student " +
//                    "values("objects[0]+",'"+objects[1]+"','"+objects[2]+"',"+objects[3]")";
            String sql = "insert into student values("+"'"+objects[0]+"','"+objects[1]+"','"+objects[2]+"','"+objects[3]+"')";
            int rowsAffected = statement.executeUpdate(sql);
            if(rowsAffected!=0){
                System.out.println("增加数据成功!");
            }

        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (SQLException e) {
                System.out.println(e);
            }
        }
    }
}

四. delete

package database;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class delete extends JFrame {
    JButton jButton;

    public delete() {
        //初始化界面
        jienmian();
        //创建一个文本框
        textArea();
        //增加按钮
        deleteButton();
        this.setVisible(true);
    }

    private void textArea() {
        // 创建一个文本框
        JTextField jTextField = new JTextField("请输入删除的学生id,完成后请回车", 20);
        jTextField.setBounds(100, 100, 300, 30);
        this.add(jTextField);

        // 为文本框添加 ActionListener 监听器
        jTextField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String text = jTextField.getText();
                //将获取到的字符串进行分割,通过空格,这里也可以不需要,因为输入的是id
                String[] Stext = text.split("\\s");
                int num;
                try {
                    num = Integer.parseInt(Stext[0]);
                    //获取到创建的模型添加数据
                    deleteUser(num);
                    //执行sql语句,从数据库中删除
                    execute_sql(num);
                } catch (NumberFormatException ei) {
                    System.out.println("字符串\"" + Stext[0] + "\"无法转换为整数");
                    ei.printStackTrace();
                }


            }
        });
        // 将文本框添加到窗口中
        this.add(jTextField);
    }

    private void deleteButton() {
        jButton = new JButton("确定");
        jButton.setBounds(240, 200, 60, 20);
        //这里用匿名内部类实现接口ActionListener
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(delete.super.rootPane, "删除信息成功");
            }
        });
        //将按钮增加到面板
        this.getContentPane().add(jButton);
    }

    public void deleteUser(int a) {

        interfaceJFrame.model.removeRow(a-1);
    }

    private void jienmian() {
        this.setSize(500, 300);
        this.setTitle("删除学生信息");
        //设置页面置顶
        this.setAlwaysOnTop(true);
        this.setLocationRelativeTo(null);
        //取消默认的居中放置,在这里我们需要添加按钮,需要设置按钮位置
        this.setLayout(null);
        this.setDefaultCloseOperation(2);
    }

    public void execute_sql(int n) {
        Connection con = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("加载驱动成功");
        } catch (Exception e) {
            System.out.println("加载驱动失败");
            System.out.println(e);
        }
        String url = "jdbc:mysql://127.0.0.1:3306/yang?useSSL=false";
        String user = "root";
        String password = "123456";
        try {
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("成功连接到数据库");
            }
            statement = con.createStatement();
            String sql1 = "use stu";
            try {
                statement.executeUpdate(sql1);
                System.out.println("正在使用stu数据库");
            } catch (SQLException e) {
                System.out.println("切换数据库失败");
                e.printStackTrace();
            }
            String sql = "DELETE FROM student " +
                    " where id="+n;
            int rowsAffected = statement.executeUpdate(sql);
            if (rowsAffected != 0) {
                System.out.println("删除数据成功!");
            }

        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (SQLException e) {
                System.out.println(e);
            }
        }
    }
}

五. update

package database;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class update extends JFrame {
    JButton jButton;

    public update() {
        //初始化界面
        jienmian();
        //创建一个文本框
        textArea();
        //增加按钮
        Button();
        this.setVisible(true);
    }

    private void textArea() {
        // 创建一个文本框
        JTextField jTextField = new JTextField("请输入要修改学生的id,列名和修改后的属性,中间用空格隔开完成后请回车", 25);
        jTextField.setBounds(100, 100, 300, 30);
        this.add(jTextField);
        // 为文本框添加 ActionListener 监听器
        jTextField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String text = jTextField.getText();
                //将获取到的字符串进行分割,通过空格
                String[] Stext = text.split("\\s");
                //这里初始化初始化y=-1,不初始化会报错,如果初始化大于0的话就算输入的第二个数据不合法程序也会运行
                int x,y =-1;
                //将获取到的列名进行相应的转化,因为我们这里需要借助表格模型更新表数据
                switch(Stext[1]) {
                    case "Name":
                        y=2;
                        break;
                    case "Sex":
                        y=3;
                        break;
                    case "Age":
                        y=4;
                        break;
                    default:
                        System.out.println("输入数据不合法!");
                }
                Object o=Stext[2];
                try {
                    x = Integer.parseInt(Stext[0]);
                    //获取到创建的模型添加数据
                    updateUser(o,x,y);
                    //执行sql语句,从数据库中修改
                    execute_sql(x,o,Stext[1]);
                } catch (NumberFormatException ei) {
                    System.out.println("字符串\"" + Stext[0] + "\"无法转换为整数");
                    ei.printStackTrace();
                }
            }
        });
        // 将文本框添加到窗口中
        this.add(jTextField);
    }

    private void Button() {
        jButton = new JButton("确定");
        jButton.setBounds(240, 200, 60, 20);
        //这里用匿名内部类实现接口ActionListener
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(update.super.rootPane, "修改信息成功");
            }
        });
        //将按钮增加到面板
        this.getContentPane().add(jButton);
    }

    public void updateUser(Object o,int x,int y) {

        interfaceJFrame.model.setValueAt(o,x-1,y-1);
        interfaceJFrame.model.fireTableCellUpdated(x-1, y-1);
    }

    private void jienmian() {
        this.setSize(500, 300);
        this.setTitle("修改学生信息");
        //设置页面置顶
        this.setAlwaysOnTop(true);
        this.setLocationRelativeTo(null);
        //取消默认的居中放置,在这里我们需要添加按钮,需要设置按钮位置
        this.setLayout(null);
        this.setDefaultCloseOperation(2);
    }

    public void execute_sql(int n,Object a,Object attribute) {
        Connection con = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("加载驱动成功");
        } catch (Exception e) {
            System.out.println("加载驱动失败");
            System.out.println(e);
        }
        String url = "jdbc:mysql://127.0.0.1:3306/yang?useSSL=false";
        String user = "root";
        String password = "123456";
        try {
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("成功连接到数据库");
            }
            statement = con.createStatement();
            String sql1 = "use stu";
            try {
                statement.executeUpdate(sql1);
                System.out.println("正在使用stu数据库");
            } catch (SQLException e) {
                System.out.println("切换数据库失败");
                e.printStackTrace();
            }
            String sql ="UPDATE  student " +
                    "SET "+ attribute+ "='"+ a +"'" +
                    "WHERE id = "+n;
            int rowsAffected = statement.executeUpdate(sql);
            if (rowsAffected != 0) {
                System.out.println("修改数据成功!");
            }

        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (SQLException e) {
                System.out.println(e);
            }
        }
    }
}

六.查询数据没整,把这个数据已经通过表格的形式展示出来了,所以没做查询这个功能。

这是下面运行后的主界面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小羊没烦恼~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值