学生管理系统(半成品)

package StudtnManger;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
public class dbConn {
    // 准备参数
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL="jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=UTF-8&useSSL=true";
    private static final String USERNAME= "root";
    private static final String PASSWORD="root";
    static{
        // 静态代码块  --  当类在加载的时候,执行静态代码块
        try {
            Class.forName(DRIVER); // 加载数据库驱动
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConn(){
        // 静态方法 类调用 是在 静态代码块 执行之后
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    public static boolean closeConn(Connection conn){
        if(conn != null){
            try {
                conn.close();
                return true;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return false;
    }

	   /* public static void main(String[] args) {
	        // 测试
	        Connection conn = dbConn.getConn();
	        System.out.println(conn); // com.mysql.jdbc.JDBC4Connection@3eb07fd3
	        if(dbConn.closeConn(conn)){
	            System.out.println("关闭成功!");
	        }
	    }*/

}

loginFrame

package StudtnManger;

import javax.swing.*;

public class LoginFrame extends JFrame {

    public LoginFrame(){
        this.init();
    }

    private void init(){
        this.setTitle("学生管理系统-登录");
        this.setBounds(200, 200, 400, 320);
        this.setVisible(true);
        this.setLayout(null); // 绝对定位

        JLabel usernameLabel = new JLabel("* 用户名:");
        JLabel passwordLabel = new JLabel("* 密码:");
        JTextField usernameText = new JTextField();
        JPasswordField passwordText = new JPasswordField();
        JButton loginBtn = new JButton("登录");

        usernameLabel.setBounds(80, 60, 60, 30);
        usernameText.setBounds(150, 60, 200, 30);
        passwordLabel.setBounds(80, 110, 50, 30);
        passwordText.setBounds(150, 110, 200, 30);
        loginBtn.setBounds(160, 160, 100, 30);

        LoginFrame that = this;
        loginBtn.addActionListener(e->{
            String username = usernameText.getText();
            String password = String.valueOf(passwordText.getPassword());
            // select * from student where number = ? and password = ?

            DBUtils dbUtils = new DBUtils();
            Student student = dbUtils.getStudent(username, password);
            if(username.equals("1001")&&password.equals("1")){
                System.out.println("登录成功!");
                JOptionPane.showMessageDialog(that, "登录成功!");
                MainFrame mainFrame = new MainFrame();
                mainFrame.username = username;
                mainFrame.test();
                that.setVisible(false);
                mainFrame.setVisible(true);
            }else{
                System.out.println("用户名或密码错误!");
                JOptionPane.showMessageDialog(that, "用户名或密码错误!");
            }
        });

        this.add(usernameLabel);
        this.add(passwordLabel);
        this.add(usernameText);
        this.add(passwordText);
        this.add(loginBtn);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.validate();
        this.revalidate();
        this.repaint();
    }

   /* public static void main(String[] args) {
        LoginFrame loginFrame = new LoginFrame();
    }*/
}

DBUtils

package StudtnManger;


import Utils.jdbcUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.FileOutputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

// 数据库表的操作类 -- 数据的增删改查
public class DBUtils {

    public Student getStudent(String number, String password) {
        Connection conn = dbConn.getConn();
        Student student = null;
        ResultSet rs = null;
        PreparedStatement pst = null;
        String sql = "select * from student where number = ? and password = ?";
        // 1001 1
        try {
            pst = conn.prepareStatement(sql);
            pst.setString(1, "1001");
            pst.setString(2, "1");
            rs = pst.executeQuery();
            if (rs.next()) {
                student = new Student();
                student.setId(rs.getInt("id"));
                student.setName(rs.getString("number"));
                student.setNumber(rs.getString("name"));
                student.setPassword(rs.getString("classname"));
                student.setClassName(rs.getString("password"));
                student.setPassword(rs.getString("phone"));
            }
            dbConn.closeConn(conn);
            return student;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
//查询所有信息
    public List<List<Object>> getAll() {
        Connection conn = dbConn.getConn();
        List<List<Object>> rows = new ArrayList<>();
        String sql = "select * from student;";
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                List<Object> row = new ArrayList<>();
                row.add(rs.getInt("id"));
                row.add(rs.getString("name"));
                row.add(rs.getString("number"));
                row.add(rs.getString("classname"));
                row.add(rs.getString("password"));
                row.add(rs.getString("phone"));
                rows.add(row);
            }
            dbConn.closeConn(conn);
            return rows;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    //查询按钮
    public List<List<Object>> getStudents(String name) {
        Connection conn = dbConn.getConn();
        List<List<Object>> rows = new ArrayList<>();
        String sql = "select * from student where name like ?";
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "%" + name + "%");
            ResultSet rs = pstmt.executeQuery();

            while (rs.next()) {
                List<Object> row = new ArrayList<>();
                row.add(rs.getInt("id"));
                row.add(rs.getString("number"));
                row.add(rs.getString("name"));
                row.add(rs.getString("classname"));
                row.add(rs.getString("password"));
                row.add(rs.getString("phone"));
                rows.add(row);
            }
            dbConn.closeConn(conn);
            return rows;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    //删除按钮
    public static void delete(int id) {
        Connection conn = dbConn.getConn();
        PreparedStatement pst = null;
        String sql = "delete from student where id=?";
        try {
            pst = conn.prepareStatement(sql);
            pst.setInt(1, id);
            int rst = pst.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //添加按钮
    public static void insert()  {

            JFrame jFrame=new JFrame();
            JPanel jPanel=new JPanel();
            JLabel jLabel=new JLabel("是否添加新的数据");
            JButton jButton = new JButton("是");
            JButton jButton1=new JButton("否");
            Dialog d1=new Dialog(jFrame,"添加",true);
            d1.setBounds(20,30,100,100);

            Box vBox = Box.createVerticalBox();
            JLabel idlabel=new JLabel("id:");
            JLabel numberlabel=new JLabel("number:");
            JLabel namelabel=new JLabel("name:");
            JLabel classnamelabel=new JLabel("classname:");
            JLabel passwordlabel=new JLabel("password:");
            JLabel phonelabel=new JLabel("phone:");

            TextField idtext=new TextField(10);
            TextField numbertext=new TextField(20);
            TextField nametext=new TextField(20);
            TextField classnametext=new TextField(20);
            TextField passwordtext=new TextField(20);
            TextField phonetext=new TextField(20);

            vBox.add(idlabel);
            vBox.add(idtext);
            vBox.add(numberlabel);
            vBox.add(numbertext);
            vBox.add(namelabel);
            vBox.add(nametext);
            vBox.add(classnamelabel);
            vBox.add(classnametext);
            vBox.add(passwordlabel);
            vBox.add(passwordtext);
            vBox.add(phonelabel);
            vBox.add(phonetext);

            JButton jButton2=new JButton("确定");
            vBox.setBounds(200,200,300,300);
            vBox.add(jButton2,BorderLayout.SOUTH);
            d1.add(vBox);

            jButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    d1.setVisible(true);
                }
            });
            //确定按钮监听
            jButton2.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {

                    Connection conn = dbConn.getConn();
                    PreparedStatement st = null;
                    String sql = "INSERT INTO `student`(`id`, `number`, `name`, `className`, `password`, `phone`) VALUES (?,?,?,?,?,?)";
                    try{st = conn.prepareStatement(sql);  //预编译,先写sql然后执行

                        st.setInt(1, Integer.parseInt(idtext.getText()));
                        st.setString(2,numbertext.getText());
                        st.setString(3, nametext.getText());
                        st.setString(4, classnametext.getText());
                        st.setString(5, passwordtext.getText());
                        st.setString(6, phonetext.getText());

                        int i = st.executeUpdate();
                        if (i > 0) {
                            JOptionPane.showMessageDialog(jFrame,"插入成功");
                        }
                    } catch(SQLException throwables)
                    {
                        throwables.printStackTrace();
                    }
                    d1.setVisible(false);
                }
            });
            jButton1.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    jFrame.setVisible(false);
                    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                }
            });

            jFrame.add(jPanel);
            jPanel.add(jLabel,BorderLayout.CENTER);
            jPanel.add(jButton);
            jPanel.add(jButton1,BorderLayout.SOUTH);
            jFrame.setBounds(200,200,300,300);
            jFrame.setVisible(true);
            jFrame.validate();
}
         //更新按钮
    public static void update(){
        JFrame jFrame=new JFrame();
        jFrame.setTitle("学生管理系统-登录");
        jFrame.setBounds(200, 200, 400, 320);
        jFrame.setVisible(true);
        jFrame.setLayout(null); // 绝对定位

        JLabel usernameLabel = new JLabel("新名字");
        JLabel passwordLabel = new JLabel("序号");

        JTextField usernameText = new JTextField();
        JTextField Text=new JTextField();

        JButton loginBtn = new JButton("确定");

        usernameLabel.setBounds(80, 60, 60, 30);
        usernameText.setBounds(150, 60, 200, 30);
        passwordLabel.setBounds(80, 110, 50, 30);
        Text.setBounds(150, 110, 200, 30);
        loginBtn.setBounds(160, 160, 100, 30);

        loginBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                Connection conn=null;
                PreparedStatement st=null;
                ResultSet rs=null;

                try {

                    conn = jdbcUtils.getConnection();
                    //使用?占位符代替参数
                    String sql ="update student set NAME=? where id=?;";

                    st=conn.prepareStatement(sql);  //预编译,先写sql然后执行

                    st.setString(1,usernameText.getText());

                    st.setInt(2, Integer.parseInt(Text.getText()));

                    int i = st.executeUpdate();
                    if(i>0){
                        JOptionPane.showMessageDialog(jFrame,"更新成功");
                        jFrame.setVisible(false);
                        jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE);
                    }
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }finally {
                    jdbcUtils.release(conn,st,rs);
                }
            }
        });

        jFrame.add(usernameLabel);
        jFrame.add(passwordLabel);
        jFrame.add(usernameText);
        jFrame.add(Text);
        jFrame.add(loginBtn);
        jFrame.validate();
        jFrame.revalidate();
        jFrame.repaint();
    }

    //下载按钮
    public static void load() {
        Connection conn = dbConn.getConn();
        String sql = "select * from student;";
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {

                int id = rs.getInt("id");
                String name = rs.getString("name");
                String number = rs.getString("number");
                String classname = rs.getString("classname");
                String password = rs.getString("password");
                String phone = rs.getString("phone");
             //   System.out.println("id:"+id+",name:"+name+",number"+number+",classname:"+classname+",password"+password+",phone"+phone);


                byte[] nameBytes = name.getBytes();
                byte[] numberBytes = number.getBytes();
                byte[] classnameBytes = classname.getBytes();
                byte[] passwordBytes = password.getBytes();
                byte[] phoneBytes = phone.getBytes();


                FileOutputStream fos =new FileOutputStream("F:\\IDEAstudy\\javastudy\\load.txt",true);
             //   FileWriter fileWriter=new FileWriter("F:\\IDEAstudy\\javastudy\\load.txt",true);
            fos.write("id:".getBytes());
            fos.write(id);
            fos.write(" ".getBytes());
            fos.write("name:".getBytes());
            fos.write(nameBytes);
                fos.write(" ".getBytes());
                fos.write("number:".getBytes());
            fos.write(numberBytes);
                fos.write(" ".getBytes());
                fos.write("classname:".getBytes());
            fos.write(classnameBytes);
                fos.write(" ".getBytes());
                fos.write("password:".getBytes());
            fos.write(passwordBytes);
                fos.write(" ".getBytes());
                fos.write("phone:".getBytes());
            fos.write(phoneBytes);
            fos.write("\r\n".getBytes());


            }
            System.out.println("写入成功");
            dbConn.closeConn(conn);
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
    }

    //导入文件

    public static void main(String[] args) {
 //       DBUtils dbUtils = new DBUtils();
//	        Student student = dbUtils.getStudent("1001", "1");
//	        if(student != null){
//	            System.out.println("登录成功!");
//	        }else{
//	            System.out.println("账号或密码错误!");
//	        }
//	        List<List<Object>> rows = dbUtils.getAll();
//	        for (List<Object> row: rows) {
//	            for (Object obj : row) {
//	                System.out.print(obj + " ");
//	            }
//	            System.out.println();
//	        }

//        List<List<Object>> rows = dbUtils.getStudents("");
//        for (List<Object> row: rows) {
//            for (Object obj : row) {
//                System.out.print(obj + " ");
//            }
//            System.out.println();

            DBUtils db=new DBUtils();
           db.load();
          //  db.update();
           // db.insert();
      //  System.out.println(db.getAll());
      //  System.out.println(db.getStudents("严"));
       // db.delete(2);

    }

}


student

package StudtnManger;
//学生类 -- 用来和数据表建立映射
public class Student {
    private int id;   // 流水号
    private String number;
    private String name;
    private String className;
    private String password;
    private String phone;

    public Student() {
    }

    public Student(String number, String name, String className, String password, String phone) {
        this.number = number;
        this.name = name;
        this.className = className;
        this.password = password;
        this.phone = phone;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", number='" + number + '\'' +
                ", name='" + name + '\'' +
                ", className='" + className + '\'' +
                ", password='" + password + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}

MainFrame

package StudtnManger;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static java.lang.Thread.sleep;

//import studentManage.user;

public class MainFrame extends JFrame implements Runnable {

    public String username;
    private JPanel bottomPanel;
    private AbstractTableModel model = null;
    private List<List<Object>> rows = null;
    private JTable table = null;
    private JScrollPane scrollPane = null;
    public  JFrame jFrame;

    public MainFrame() {
        this.init();
    }

    public void test() {
        this.bottomPanel.add(new JLabel(this.username));
        System.out.println(username);
        this.bottomPanel.validate();
    }

    public void init() {
        this.setTitle("学生管理系统-主界面");
        this.setBounds(200, 200, 600, 480);
        this.setVisible(true);
        this.setLayout(new BorderLayout());

        // 创建三个面板容器
        JPanel topPanel = new JPanel();
        JPanel centerPanel = new JPanel();
        bottomPanel = new JPanel();

        // topPanel
        topPanel.setLayout(new FlowLayout());
        // 组件
        JTextField searchText = new JTextField(10);
        JButton searchBtn = new JButton("搜索");
        JButton addBtn = new JButton("添加");
        JButton editBtn = new JButton("编辑");
        JButton deleteBtn = new JButton("删除");
        JButton uploadBtn = new JButton("上传");
        JButton downBtn = new JButton("下载");
        JButton updateBtn = new JButton("更新");

        topPanel.add(searchText);
        topPanel.add(searchBtn);
        topPanel.add(addBtn);
        topPanel.add(editBtn);
        topPanel.add(deleteBtn);
        topPanel.add(uploadBtn);
        topPanel.add(downBtn);
        topPanel.add(updateBtn);
        // centerPanel
        centerPanel.setLayout(new BorderLayout());
        // 写一个表格,准备一些静态数据
        List<String> headers = new ArrayList<>();
        headers.add("序号");
        headers.add("name");
        headers.add("number");
        headers.add("className");
        headers.add("password");
        headers.add("phone");
        // 表体
        DBUtils dbUtils = new DBUtils();
        rows = dbUtils.getAll();
        // 表格的数据容器
        model = new AbstractTableModel() {
            @Override
            public int getRowCount() {
                return rows.size();
            }

            @Override
            public int getColumnCount() {
                return headers.size();
            }

            @Override
            public Object getValueAt(int rowIndex, int columnIndex) {
                return rows.get(rowIndex).get(columnIndex);
            }

            @Override
            public String getColumnName(int column) {
                return headers.get(column);
            }
        };
        table = new JTable(model);
        scrollPane = new JScrollPane(table);
        centerPanel.add(scrollPane);

        searchText.addActionListener(e -> {
            String name = searchText.getText();
            rows = dbUtils.getStudents(name);
            model = new AbstractTableModel() {
                @Override
                public int getRowCount() {
                    return rows.size();
                }

                @Override
                public int getColumnCount() {
                    return headers.size();
                }

                @Override
                public Object getValueAt(int rowIndex, int columnIndex) {
                    return rows.get(rowIndex).get(columnIndex);
                }

                @Override
                public String getColumnName(int column) {
                    return headers.get(column);
                }
            };
            table = new JTable(model);
            centerPanel.remove(scrollPane);
            scrollPane = new JScrollPane(table);
            centerPanel.add(scrollPane);
            centerPanel.validate();
        });
        //查询(模糊查询还未实现)
        searchBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(searchText.getText()!="0") {
                    JOptionPane.showMessageDialog(jFrame, dbUtils.getStudents(searchText.getText()));
                    centerPanel.validate();
                }else{
                    JOptionPane.showMessageDialog(jFrame, "未查找到输入的信息");
                }
            }
        });
        //删除
        deleteBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (searchText.getText() == "") {
                    JOptionPane.showMessageDialog(jFrame,"请在输入框输入要删除的id");
                } else {
                    dbUtils.delete(Integer.parseInt(searchText.getText()));
                    JOptionPane.showMessageDialog(jFrame,"删除成功");
                    searchText.setText("");
                    dbUtils.getAll();
                }
            }
        });
        //插入按钮
        addBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                    DBUtils db = new DBUtils();
                    db.insert();
            }
        });
        //编辑按钮
        editBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                dbUtils.update();
            }
        });
        //更新按钮
        updateBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                jFrame.revalidate();
            }
        });

        //下载按钮
        downBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                dbUtils.load();
                JOptionPane.showMessageDialog(jFrame,"下载成功,文件存放在F:\\IDEAstudy\\javastudy\\load.txt中");
            }
        });

        // bottomPanel
        bottomPanel.setLayout(new FlowLayout());
        TextField textField = new TextField(15);
        bottomPanel.add(textField,BorderLayout.CENTER);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        long current = System.currentTimeMillis();
                        Date date = new Date(current);
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                        textField.setText(format.format(date));
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


        this.add(topPanel, BorderLayout.NORTH);
        this.add(centerPanel);
        this.add(bottomPanel, BorderLayout.SOUTH);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.validate();
    }

    public static void main(String[] args) {
        // LoginFrame loginFrame = new LoginFrame();

        MainFrame mainFrame = new MainFrame();
    }

    @Override
    public void run() {
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

祈愿lucky

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

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

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

打赏作者

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

抵扣说明:

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

余额充值