学生信息管理系统(jdbc操作MySQL)

来源:互联网 发布:小米床垫怎么样 知乎 编辑:程序博客网 时间:2024/05/23 15:37

MySQL

这里写图片描述

StudentManage

这里写图片描述

    // 定义控件    JPanel jp1, jp2;    JLabel jl1;    JButton jb1, jb2, jb3, jb4;    // JScrollPane jsp;    JTextField jtf;    StuModel sm;    // 定义连接数据库操作    PreparedStatement ps = null;    Connection ct = null;    ResultSet rs = null;    JTable jt = null;    JScrollPane jsp = null;    public static void main(String[] args) {        // TODO Auto-generated method stub        StuManage test = new StuManage();    }    // 构造函数    public StuManage()     {     jp1=new JPanel();     jtf=new JTextField(10);     jb1=new JButton("查询");     jb1.addActionListener(this);     jl1=new JLabel("请输入名字");     //把各个控件加入到jp1     jp1.add(jl1);     jp1.add(jtf);     jp1.add(jb1);     jp2=new JPanel();     jb2=new JButton("添加");     jb2.addActionListener(this);     jb3=new JButton("修改");     jb3.addActionListener(this);     jb4=new JButton("删除");     jb4.addActionListener(this);     //把各个按钮加入到jp2     jp2.add(jb2);     jp2.add(jb3);     jp2.add(jb4);     //创建一个数据模型对象    sm=new StuModel();     // 初始化JTable     jt=new JTable(sm);     //初始化jsp JScrollPane     jsp=new JScrollPane(jt);     //把jsp放入到 jfame     this.add(jsp);     this.add(jp1,"North");     this.add(jp2,"South");     this.setSize(400,300);     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     this.setVisible(true);     }    public void actionPerformed(ActionEvent arg0) {        // TODO Auto-generated method stub        // 判断是那个按钮被按下 .jb1 和 actonperformed必须在同一个类里面        if (arg0.getSource() == jb1) {            System.out.println("用户想查询");            // 因为把表的数据封装在StuModel中了。我们就很容易完成查询            String name = this.jtf.getText().trim();            // 写一个sql语句            // String sql=" select *from stu where stuName='"+name+"'";            // 模糊查询            String sql = " select *from stu where stuName like '%" + name + "%'";            // 构建新的数据模型类,并更新            sm = new StuModel(sql);            // 更新Jtable            jt.setModel(sm);        }        // 当用户点击查询        else if (arg0.getSource() == jb2) {            StuAddDialog sa = new StuAddDialog(this, "添加学生", true);            // 重新获得数据类型            // 构建新的数据模型类,并更新            sm = new StuModel();            // 更新Jtable            jt.setModel(sm);        }        // 点击的是修改        else if (arg0.getSource() == jb3) {            // 用户希望修改            int rowNum = this.jt.getSelectedRow();            if (rowNum == -1) {                // 提示                JOptionPane.showMessageDialog(this, "选择一行");                return;            }            // 显示修改对话框            new StuUpdDialog(this, "修改学生", true, sm, rowNum);            // 构建新的数据模型类,并更新            sm = new StuModel();            // 更新Jtable            jt.setModel(sm);        }        // 点击的是删除        else if (arg0.getSource() == jb4) {            // 说明用户希望删除记录            // 得到该学生的id            // 如果该用户一行都没有选择就返回-1            int rowNum = this.jt.getSelectedRow();            if (rowNum == -1) {                // 提示                JOptionPane.showMessageDialog(this, "选择一行");                return;            }            // 得到学生的编号            String stuId = (String) sm.getValueAt(rowNum, 0); // 返回编号            // System.out.println("id="+stuId);            // 连接数据库完成删除任务            try {                // 加载驱动                Class.forName("com.mysql.jdbc.Driver");                ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/myhaha", "root", "mysql520");                // 准备陈说语句 .注意要用 use spdb1; 否则会报表不存                ps = ct.prepareStatement("delete from mybaby where stuid=?");                ps.setString(1, stuId);                // 执行查询                ps.executeUpdate();            } catch (Exception e) {                // TODO: handle exception                e.printStackTrace();            } finally {                // 关闭                try {                    if (rs != null)                        rs.close();                    if (ps != null)                        ps.close();                    if (ct != null)                        ct.close();                } catch (Exception e) {                    // TODO: handle exception                    e.printStackTrace();                }                // 构建新的数据模型类,并更新                sm = new StuModel();                // 更新Jtable                jt.setModel(sm);            }        }    }

StuModel

import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.Vector;import javax.swing.table.*;public class StuModel extends AbstractTableModel {    // rowData用来存放行数据    // columnNames存放列名    Vector rowData, columnNames;    // 定义连接数据库操作    PreparedStatement ps = null;    Connection ct = null;    ResultSet rs = null;    public void init(String sql) {        if (sql.equals("")) {            sql = " select *from mybaby";        }        // 中间        columnNames = new Vector();        columnNames.add("学号");        columnNames.add("姓名");        columnNames.add("性别");        columnNames.add("年龄");        columnNames.add("籍贯");        columnNames.add("系别");        rowData = new Vector();        // 从数据库中取出数据        rowData = new Vector();        try {            // 加载驱动            Class.forName("com.mysql.jdbc.Driver");            ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/myhaha", "root", "mysql520");            // 准备陈说语句 .注意要用 use spdb1; 否则会报表不存            ps = ct.prepareStatement(sql);            // 执行查询            rs = ps.executeQuery();            // 返回查询结果            while (rs.next()) {                // rowData                Vector hang = new Vector();                hang.add(rs.getString(1));                hang.add(rs.getString(2));                hang.add(rs.getString(3));                hang.add(rs.getInt(4));                hang.add(rs.getString(5));                hang.add(rs.getString(6));                // 加入到rowData                rowData.add(hang);            }        } catch (Exception e) {            // TODO: handle exception            e.printStackTrace();        } finally {            // 关闭资源            try {                if (rs != null) {                    rs.close();                }                if (ps != null) {                    ps.close();                }                if (ct != null) {                    ct.close();                }            } catch (Exception e) {                // TODO: handle exception            }        }    }    public void addStu(String sql) {        // 根据用户输入的SQL语句完成添加任务    }    // 通过传递的sql语句来获得数据模型    public StuModel(String sql) {        this.init(sql);    }    // 做一个构造函数初始化数据模型    public StuModel() {        this.init("");    }    // 得到共有多少列    public int getColumnCount() {        // TODO Auto-generated method stub        return this.columnNames.size();        // return 0;    }    // 得到共有多少行    public int getRowCount() {        // TODO Auto-generated method stub        return this.rowData.size();        // return 0;    }    // 得到某行某列的数据    public Object getValueAt(int arg0, int arg1) {        // TODO Auto-generated method stub        return ((Vector) this.rowData.get(arg0)).get(arg1); // arg0表行 arg1 表示列        // return null;    }    // 重写方法 getColumnName    @Override    public String getColumnName(int column) {        // TODO Auto-generated method stub        return (String) this.columnNames.get(column);    }}

StuAddDialog.java

这里写图片描述

/**  * 修改学生信息 */import java.sql.*;import java.awt.event.*;import java.awt.*;import javax.swing.*;public class StuAddDialog extends JDialog implements ActionListener {    // 定义我需要的swing组件    JLabel jl1, jl2, jl3, jl4, jl5, jl6;    JButton jb1, jb2;    JTextField jtf1, jtf2, jtf3, jtf4, jtf5, jtf6;    JPanel jp1, jp2, jp3;    // owner 它的父窗口    // title 窗口名    // modal 指定的模式窗口,还有非模式窗口    public StuAddDialog(Frame owner, String title, boolean modal) {        super(owner, title, modal); // 调用父类的构造方法        jl1 = new JLabel("学号");        jl2 = new JLabel("姓名");        jl3 = new JLabel("性别");        jl4 = new JLabel("年龄");        jl5 = new JLabel("籍贯");        jl6 = new JLabel("系别");        jtf1 = new JTextField();        jtf2 = new JTextField();        jtf3 = new JTextField();        jtf4 = new JTextField();        jtf5 = new JTextField();        jtf6 = new JTextField();        jb1 = new JButton("添加");        // 注册监听        jb1.addActionListener(this);        jb2 = new JButton("取消");        jb2.addActionListener(this);        jp1 = new JPanel();        jp2 = new JPanel();        jp3 = new JPanel();        // 设置布局        jp1.setLayout(new GridLayout(6, 1));        jp2.setLayout(new GridLayout(6, 1));        // 添加组件        jp1.add(jl1);        jp1.add(jl2);        jp1.add(jl3);        jp1.add(jl4);        jp1.add(jl5);        jp1.add(jl6);        jp2.add(jtf1);        jp2.add(jtf2);        jp2.add(jtf3);        jp2.add(jtf4);        jp2.add(jtf5);        jp2.add(jtf6);        jp3.add(jb1);        jp3.add(jb2);        this.add(jp1, BorderLayout.WEST);        this.add(jp2, BorderLayout.CENTER);        this.add(jp3, BorderLayout.SOUTH);        // 展现        this.setSize(300, 200);        //        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        this.setVisible(true);    }    public void actionPerformed(ActionEvent e) {        // TODO Auto-generated method stub        if (e.getSource() == jb1) {            // 对用户点击添加按钮后的响应动作            // 连接数据库            Connection conn = null;            Statement stmt = null;            ResultSet rs = null;            PreparedStatement pstmt = null;            // 连接数据库,判断数据库是否合法            try {                // 1:加载驱动                Class.forName("com.mysql.jdbc.Driver");                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myhaha", "root", "mysql520");                // 4:编辑语句对象                String strsql = "insert into mybaby values(?,?,?,?,?,?)";                pstmt = conn.prepareStatement(strsql);                // 给参数赋值                pstmt.setString(1, jtf1.getText());                pstmt.setString(2, jtf2.getText());                pstmt.setString(3, jtf3.getText());                pstmt.setString(4, jtf4.getText());                pstmt.setString(5, jtf5.getText());                pstmt.setString(6, jtf6.getText());                // 4执行操作                pstmt.executeUpdate();                this.dispose(); // 关闭学生对话框            } catch (Exception e1) {                // TODO: handle exception                e1.printStackTrace();            } finally {                // 释放资源                try {                    if (rs != null)                        rs.close();                    if (stmt != null)                        stmt.close();                    if (conn != null)                        conn.close();                } catch (Exception e2) {                    // TODO: handle exception                    e2.printStackTrace();                }            }        } else if (e.getSource() == jb2) {            try {                this.dispose(); // 关闭学生对话框            } catch (Exception e3) {                // TODO: handle exception                e3.printStackTrace();            }        }    }}

StuUpdDialog.java

这里写图片描述

import java.sql.*;import java.awt.event.*;import java.awt.*;import javax.swing.*;public class StuUpdDialog extends JDialog implements ActionListener {    /**      *       */    private static final long serialVersionUID = 5111753693908579465L;    // 定义我需要的swing组件    JLabel jl1, jl2, jl3, jl4, jl5, jl6;    JButton jb1, jb2;    JTextField jtf1, jtf2, jtf3, jtf4, jtf5, jtf6;    JPanel jp1, jp2, jp3;    // owner 它的父窗口    // title 窗口名    // modal 指定的模式窗口,还有非模式窗口    public StuUpdDialog(Frame owner, String title, boolean modal, StuModel sm, int rowNums) {        super(owner, title, modal); // 调用父类的构造方法        jl1 = new JLabel("学号");        jl2 = new JLabel("姓名");        jl3 = new JLabel("性别");        jl4 = new JLabel("年龄");        jl5 = new JLabel("籍贯");        jl6 = new JLabel("系别");        jtf1 = new JTextField();        // 初始化数据        jtf1.setText((String) sm.getValueAt(rowNums, 0));        // 让jtf1不能修改        jtf1.setEditable(false);        jtf2 = new JTextField();        jtf2.setText((String) sm.getValueAt(rowNums, 1));        jtf3 = new JTextField();        jtf3.setText((String) sm.getValueAt(rowNums, 2));        jtf4 = new JTextField();        jtf4.setText(sm.getValueAt(rowNums, 3).toString());        jtf5 = new JTextField();        jtf5.setText((String) sm.getValueAt(rowNums, 4));        jtf6 = new JTextField();        jtf6.setText((String) sm.getValueAt(rowNums, 5));        jb1 = new JButton("修改");        // 注册监听        jb1.addActionListener(this);        jb2 = new JButton("取消");        jb2.addActionListener(this);        jp1 = new JPanel();        jp2 = new JPanel();        jp3 = new JPanel();        // 设置布局        jp1.setLayout(new GridLayout(6, 1));        jp2.setLayout(new GridLayout(6, 1));        // 添加组件        jp1.add(jl1);        jp1.add(jl2);        jp1.add(jl3);        jp1.add(jl4);        jp1.add(jl5);        jp1.add(jl6);        jp2.add(jtf1);        jp2.add(jtf2);        jp2.add(jtf3);        jp2.add(jtf4);        jp2.add(jtf5);        jp2.add(jtf6);        jp3.add(jb1);        jp3.add(jb2);        this.add(jp1, BorderLayout.WEST);        this.add(jp2, BorderLayout.CENTER);        this.add(jp3, BorderLayout.SOUTH);        // 展现        this.setSize(300, 200);        //        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        this.setVisible(true);    }    public void actionPerformed(ActionEvent e) {        // TODO Auto-generated method stub        if (e.getSource() == jb1)        {            // 对用户点击修改按钮后的响应动作            // 连接数据库            Connection conn = null;            Statement stmt = null;            ResultSet rs = null;            PreparedStatement pstmt = null;            // 连接数据库,判断数据库是否合法            try {                // 1:加载驱动                Class.forName("com.mysql.jdbc.Driver");                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myhaha", "root", "mysql520");                // 4:编辑语句对象                String strsql = "update mybaby set stuName=?, stuSex=?,"                        + "stuAge=?, sutJg=?, stuDept=? where stuId=? ";                pstmt = conn.prepareStatement(strsql);                // 给?号赋值                pstmt.setString(1, jtf2.getText());                pstmt.setString(2, jtf3.getText());                pstmt.setString(3, jtf4.getText());                pstmt.setString(4, jtf5.getText());                pstmt.setString(5, jtf6.getText());                pstmt.setString(6, jtf1.getText());                // 4执行操作                pstmt.executeUpdate();                this.dispose(); // 关闭学生对话框            } catch (Exception e1) {                // TODO: handle exception                e1.printStackTrace();            } finally {                // 释放资源                try {                    if (rs != null)                        rs.close();                    if (stmt != null)                        stmt.close();                    if (conn != null)                        conn.close();                } catch (Exception e2) {                    // TODO: handle exception                    e2.printStackTrace();                }            }        } else if (e.getSource() == jb2) {            try {                this.dispose(); // 关闭学生对话框            } catch (Exception e3) {                // TODO: handle exception                e3.printStackTrace();            }        }    }}

Java操作 mysql:往数据表里面增加一行数据

初步代码:

        try {            // 1.注册驱动            DriverManager.registerDriver(new com.mysql.jdbc.Driver());            // Class.forName("com.mysql.jdbc.Driver");//推荐使用这种方式            // System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");            // 2.建立连接            // url 格式:JDBC:子协议:子名称//主机名:端口/数据库名            Connection ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/myhaha", "root", "mysql520");            // 3.创建语句            Statement sm = ct.createStatement();            // 4.执行语句            int i = sm.executeUpdate("insert into mybaby values('李青雯','女','国贸2')");            // 5.判断结果            if (i == 1) {                System.out.println("haha");            } else {                System.out.println("false");            }            // 6.关闭资源(ResultSet,Statement,Connection)            sm.close();            ct.close();        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }

代码增强:

/**  * 好的jdbc代码写法 */import java.sql.*;public class test2 {    static String url = "jdbc:mysql://localhost:3306/mytestbase";    static String user = "root";    static String password = "mysql520";    static Connection ct = null;    static Statement sm = null;    public static void main(String[] args) throws Exception {        // TODO Auto-generated method stub        try {            // 注册驱动            Class.forName("com.mysql.jdbc.Driver");            // 建立连接            ct = DriverManager.getConnection(url, user, password);            // 创建语句            sm = ct.createStatement();            // 执行语句            int i = sm.executeUpdate("insert into myxixi values('5','林冲')");            // 判断结果            if (i == 1) {                System.out.println("ok");            } else {                System.out.println("false");            }            ;        } catch (ClassNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } finally {            try {                if (sm != null)                    sm.close();            } finally {                try {                    if (ct != null)                        ct.close();                } catch (Exception e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }}
0 0