java用swing实现超市管理系统jdbc(多图)附源码

首先是登录界面,可以选择不同的权限,管理员或者收银员
java用swing实现超市管理系统jdbc(多图)附源码_第1张图片管理员权限分为以下3个
java用swing实现超市管理系统jdbc(多图)附源码_第2张图片增删改查都差不多
java用swing实现超市管理系统jdbc(多图)附源码_第3张图片

可以在上方查看我的信息和切换账户,切换的话直接回到登录界面,然后该界面消失
java用swing实现超市管理系统jdbc(多图)附源码_第4张图片
这是收银员模块
商品可以加入购物车,也可以直接购买,无论加没加购物车,浏览过得商品都会有记录,注:浏览记录和购买记录都是临时变量,用集合做的没连数据库
java用swing实现超市管理系统jdbc(多图)附源码_第5张图片直接购买界面
java用swing实现超市管理系统jdbc(多图)附源码_第6张图片购物车购买界面
java用swing实现超市管理系统jdbc(多图)附源码_第7张图片
加入购物车界面
java用swing实现超市管理系统jdbc(多图)附源码_第8张图片浏览记录
java用swing实现超市管理系统jdbc(多图)附源码_第9张图片支付过程分为确认购买,会员登录,然后选择支付方式,余额够的话就支付,然后加会员积分,减掉余额,生成订单信息,注意价格计算算折扣哦
截图太麻烦,这里只截一张
java用swing实现超市管理系统jdbc(多图)附源码_第10张图片
这是排行榜,点击刷新会更新最新的排行
这是订单查询,输入一个数字就可以查到相关的交易信息
java用swing实现超市管理系统jdbc(多图)附源码_第11张图片4的查询结果如下
java用swing实现超市管理系统jdbc(多图)附源码_第12张图片
这是代码结构,页面控制层,服务层,数据库连接层
只传几个核心模块,需要全部源码的可以直接找我
因为后期懒了,收银员模块没有分层,直接在控制层里调的数据库
在说一下代码有几个bug,懒得改了:
1,购物车添加,会重复
2,东西买完以后,状态不会自动下架
其他bug欢迎大家提醒

java用swing实现超市管理系统jdbc(多图)附源码_第13张图片管理员界面

package controller;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import java.awt.*;
import java.util.Vector;

/**
 * @ author Edward.wei
 * @date: 2021年03月29日22:36
 * @describtion:
 */
public class ManagerHomePage extends JFrame implements PageChange{
    private JTabbedPane tabbedPane;
    private JPanel panel1;
    private JPanel panel2;
    private JPanel panel3;
    private JPanel topMainPanle;
    private JTable goodsTypeTable;
    private GT gt = new GT();
    private G g = new G();
    private Vip vip = new Vip();
    Container contentPane = getContentPane();
    public ManagerHomePage(){
        init();
    }
    private void init(){
        //设置窗口
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("超市管理系统");
        setSize(800,500);
        setResizable(false);
        setLocationRelativeTo(null);
    }
    @Override
    public void homePage(String username){
        //标题部分主面板
        topMainPanle =  new JPanel(new GridLayout(1,3,1,1));
                //     1.显示用户
        JLabel welcome = new JLabel("欢迎用户: "+username);
        welcome.setFont(new Font("黑体",2,20));
        welcome.setForeground(Color.RED);
                //     2.主标题
        JLabel mainTitle = new JLabel("超市管理系统");
        mainTitle.setForeground(Color.BLUE);
        mainTitle.setFont(new Font("黑体",2,30));
        //工具选框
        JPanel mainPanel = new JPanel(new FlowLayout());
        JComboBox<String> tool = new JComboBox<>();
        tool.addItem("我的信息");
        tool.addItem("切换账户");
        tool.addItem("有待开发");
        JButton mainButton = new JButton("确定");
        mainButton.addActionListener((e)->{
            int selectedIndex = tool.getSelectedIndex();
            switch (selectedIndex){
                case 0:
                    TopTool.myInformation(username,"管理员","D:\\Java\\SM\\superShoppingSystem\\resources\\manager01.jpg");
                    break;
                case 1:
                    Login login = new Login();
                    login.logInGUI();
                    dispose();
                    break;
                default:
                    break;
            }
        });
        mainPanel.add(tool);
        mainPanel.add(mainButton);
        topMainPanle.add(welcome);
        topMainPanle.add(mainTitle);
        topMainPanle.add(mainPanel);

        /** 以下为管理员页面 ,分为 1.商品类型管理  2,商品管理  3,会员管理*/

        //主体面板
        tabbedPane = new JTabbedPane(JTabbedPane.LEFT);
        //    1. 商品类型管理   添加,修改,删除
        panel1 = new JPanel(new BorderLayout());//panel1为商品类型管理面板 分为表格部分和按钮部分
        JPanel buttonPanel = new JPanel();//按钮面板
        JPanel tablePanel1 = new JPanel(new BorderLayout());//表格面板
        //        创建表格
        goodsTypeTable = new JTable(new MytableModel1());
        //        创建按钮
        JButton add = new JButton("添加");
        add.addActionListener((e -> {
            gt.addItem();
        }));
        JButton modify = new JButton("修改");
        modify.addActionListener((e -> {
            gt.modifyItem();
        }));
        JButton delete = new JButton("删除");
        delete.addActionListener((e)->{
            gt.deleteItem();
        });
        JButton updata = new JButton("更新");
        updata.addActionListener(e->{
            goodsTypeTable.setModel(new MytableModel1());//实现更新

        });
        //添加 按钮 给按钮面板
        buttonPanel.add(add);
        buttonPanel.add(modify);
        buttonPanel.add(delete);
        buttonPanel.add(updata);
        /*用JScrollPane装载JTable,这样超出范围的列就可以通过滚动条来查看*/
        goodsTypeTable.setPreferredScrollableViewportSize(new Dimension(500,200));
        JScrollPane js =new JScrollPane(goodsTypeTable);
        //添加 表格 给表格面板
        tablePanel1.add(goodsTypeTable.getTableHeader(),BorderLayout.NORTH);
        tablePanel1.add(js,BorderLayout.CENTER);






        //2.商品管理
        panel2 = new JPanel(new BorderLayout());
        //   表格面板
        JPanel tablepanel2 = new JPanel(new BorderLayout());
        //      创建表格
        JTable goodsTable = new JTable(new MytableModel2());
        //   按钮面板
        JPanel buttonPanel2 = new JPanel();
        //       创建按钮
        JButton goodAdd = new JButton("添加");
        goodAdd.addActionListener((e -> {
            g.addItem();
        }));
        JButton goodDelete = new JButton("删除");
        goodDelete.addActionListener(e->{
            g.deleteItem();
        });
        JButton goodModify = new JButton("修改");
        goodModify.addActionListener(e->{
            g.modifyItem();
        });
        JButton goodUpdate = new JButton("更新");
        goodUpdate.addActionListener(e->{
            goodsTable.setModel(new MytableModel2());
        });
        //将按钮添加到按钮面板
        buttonPanel2.add(goodAdd);
        buttonPanel2.add(goodDelete);
        buttonPanel2.add(goodModify);
        buttonPanel2.add(goodUpdate);
        //将表格添加到表格面板
        tablepanel2.add(goodsTable.getTableHeader(),BorderLayout.NORTH);
        tablepanel2.add(goodsTable,BorderLayout.CENTER);






        panel3 = new JPanel(new BorderLayout());
        //   表格面板
        JPanel tablepanel3 = new JPanel(new BorderLayout());
        //      创建表格
        JTable vipTable = new JTable(new MytableModel3());
        //   按钮面板
        JPanel buttonPanel3 = new JPanel();
        //       创建按钮
        JButton vipAdd = new JButton("添加");
        vipAdd.addActionListener((e -> {
            vip.addItem();
        }));
        JButton vipDelete = new JButton("删除");
        vipDelete.addActionListener(e->{
            vip.deleteItem();
        });
        JButton vipModify = new JButton("修改");
        vipModify.addActionListener(e->{
            vip.modifyItem();
        });
        JButton vipUpdate = new JButton("更新");
        vipUpdate.addActionListener(e->{
            vipTable.setModel(new MytableModel3());
        });
        JButton vipAddBalance = new JButton("充值");
        vipAddBalance.addActionListener((e)->{
            vip.addBalance();
        });
        //将按钮添加到按钮面板
        buttonPanel3.add(vipAdd);
        buttonPanel3.add(vipDelete);
        buttonPanel3.add(vipModify);
        buttonPanel3.add(vipUpdate);
        buttonPanel3.add(vipAddBalance);
        //将表格添加到表格面板
        tablepanel3.add(vipTable.getTableHeader(),BorderLayout.NORTH);
        tablepanel3.add(vipTable,BorderLayout.CENTER);
        //1.
        panel1.add(buttonPanel,BorderLayout.SOUTH);
        panel1.add(tablePanel1,BorderLayout.CENTER);
        //2.
        panel2.add(buttonPanel2,BorderLayout.SOUTH);
        panel2.add(tablepanel2,BorderLayout.CENTER);
        //3.
        panel3.add(buttonPanel3,BorderLayout.SOUTH);
        panel3.add(tablepanel3,BorderLayout.CENTER);
        // 主页菜单栏
        tabbedPane.add("商品类型管理", panel1);
        tabbedPane.addTab("商品管理", panel2);
        tabbedPane.addTab("会员管理", panel3);
        // 核心添加
        contentPane.add(tabbedPane, BorderLayout.CENTER);
        contentPane.add(topMainPanle,BorderLayout.NORTH);
        // 设置可见
        setVisible(true);
    }


    private class MytableModel1 extends AbstractTableModel {
        Vector<String> colum = new Vector<>();
        Vector<Vector> good = gt.updataItem();
        public MytableModel1(){
            String[] columnNames = {"类型ID","商品名称","父类ID","是否为父类","类型状态","更新时间"};
            for (String columnName : columnNames) {
                colum.add(columnName);
            }

        }
        @Override
        public int getRowCount() {
            return good.size();
        }
        @Override
        public int getColumnCount() {
            return colum.size();
        }
        @Override
        public String getColumnName(int column){
            return colum.get(column);
        }
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return good.get(rowIndex).get(columnIndex);
    }
    }
    private class MytableModel2 extends AbstractTableModel {
        Vector<String> colum = new Vector<>();
        Vector<Vector> good = g.updataItem();
        public MytableModel2(){
            String[] columnNames = {"ID","商品名称","类型","数量","价格","状态","折扣","更新时间"};
            for (String columnName : columnNames) {
                colum.add(columnName);
            }

        }
        @Override
        public int getRowCount() {
            return good.size();
        }
        @Override
        public int getColumnCount() {
            return colum.size();
        }
        @Override
        public String getColumnName(int column){
            return colum.get(column);
        }
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return good.get(rowIndex).get(columnIndex);
        }
    }


    private class MytableModel3 extends AbstractTableModel {
        Vector<String> colum = new Vector<>();
        Vector<Vector> good = vip.updataItem();
        public MytableModel3(){
            String[] columnNames = {"ID","姓名","密码","头像","联系方式","积分","余额","更新时间"};
            for (String columnName : columnNames) {
                colum.add(columnName);
            }
        }

        @Override
        public int getRowCount() {
            return good.size();
        }

        @Override
        public int getColumnCount() {
            return colum.size();
        }
        public String getColumnName(int column){
            return colum.get(column);
        }

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

收银员界面

package controller;

import util.DBulit;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
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.beans.Transient;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Vector;
import java.util.concurrent.TimeUnit;

/**
 * @ author Edward.wei
 * @date: 2021年04月10日19:38
 * @describtion:
 */
public class CashierHomePage implements PageChange {
    private JFrame frame;
    private JPanel leftMenu;
    private JTabbedPane tabbedPane;
    G g = new G();
    Buy b = new Buy();
    Vector<Vector> vector = new Vector<>();
    Vector<Vector> vector2 = new Vector<>();
    JTable shoppingCartTable = new JTable(new MyModel2());//购物车表
    @Override
    public void homePage(String username) {
        //设置窗口
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("超市管理系统");
        frame.setSize(800,500);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        //
        JPanel topMainPanle =  new JPanel(new GridLayout(1,3,1,1));
        JLabel welcome = new JLabel("欢迎用户: "+username);
        welcome.setFont(new Font("黑体",2,20));
        welcome.setForeground(Color.RED);
        //主标题
        JLabel mainTitle = new JLabel("超市管理系统");
        mainTitle.setForeground(Color.BLUE);
        mainTitle.setFont(new Font("黑体",2,30));
        //工具选框
        JPanel mainPanel = new JPanel(new FlowLayout());
        JComboBox<String> tool = new JComboBox<>();
        tool.addItem("我的信息");
        tool.addItem("切换账户");
        tool.addItem("有待开发");
        JButton mainButton = new JButton("确定");
        mainButton.addActionListener((e)->{
            int selectedIndex = tool.getSelectedIndex();
            switch (selectedIndex){
                case 0:
                    TopTool.myInformation(username,"收银员","D:\\Java\\SM\\superShoppingSystem\\resources\\cashier01.jpg");
                    break;
                case 1:
                    Login login = new Login();
                    login.logInGUI();
                    frame.dispose();
                    break;
                default:
                    break;
            }

        });
        mainPanel.add(tool);
        mainPanel.add(mainButton);
        topMainPanle.add(welcome);
        topMainPanle.add(mainTitle);
        topMainPanle.add(mainPanel);
        //
        tabbedPane = new JTabbedPane(JTabbedPane.LEFT);
        tabbedPane.setBackground(null);
        tabbedPane.setOpaque(false);
        JPanel panel1 = new JPanel(new BorderLayout());
        //购买管理分为表格部分(商品信息)和按钮部分,按钮部分分为 直接购买,浏览,购物车,浏览记录,更新
        JPanel tablePanel1 = new JPanel(new BorderLayout());
        JPanel buttonPanel1 = new JPanel(new FlowLayout());
        // 造表
        JTable goodsTable = new JTable(new MyModel1());

        shoppingCartTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(e.getClickCount() == 1){
                    int columnIndex = shoppingCartTable.columnAtPoint(e.getPoint()); //获取点击的列
                    int selectedRow = shoppingCartTable.getSelectedRow();
                    int rowIndex = shoppingCartTable.rowAtPoint(e.getPoint()); //获取点击的行
                    if(columnIndex == 0) {//第0列时,执行代码
//                        if(shoppingCartTable.getValueAt(rowIndex,columnIndex) == null){ //如果未初始化,则设置为false
//                            vector.get(columnIndex).set(0,false);
//                            shoppingCartTable.setModel(new MyModel2());
//                        }
                        if(((Boolean)shoppingCartTable.getValueAt(rowIndex,columnIndex)).booleanValue()){ //原来选中
                            vector.get(selectedRow).set(0,false);
                            shoppingCartTable.setModel(new MyModel2());
                        }
                        else {//原来未选中
                            vector.get(selectedRow).set(0,true);
                            shoppingCartTable.setModel(new MyModel2());
                        }
                    }

                }
            }
        });
        // 造按钮
        JButton buy = new JButton("直接购买");
        buy.addActionListener((e)->{
            b.buy();
        });
        JButton browse = new JButton("加入购物车");
        browse.addActionListener((e)->{
            // bug1:一旦没添加数量,这就赋不了值,然后购物车表格就排不了,崩了
            //改:搞了一个初始值,如果数量不对会添加一个全空的数据
            broswse();
            }
        );
        JButton browsingHistory = new JButton("浏览记录");
        browsingHistory.addActionListener((e)->{
            browseHistory();



        });
        JButton update = new JButton("更新");
        update.addActionListener((e)->{
            goodsTable.setModel(new MyModel1());
        });

        //添加
        tablePanel1.add(goodsTable.getTableHeader(),BorderLayout.NORTH);
        tablePanel1.add(goodsTable,BorderLayout.CENTER);
        buttonPanel1.add(buy);
        buttonPanel1.add(browse);
        buttonPanel1.add(browsingHistory);
        buttonPanel1.add(update);
        panel1.add(tablePanel1,BorderLayout.CENTER);
        panel1.add(buttonPanel1,BorderLayout.SOUTH);

        //
        JPanel panel2 = new JPanel();
        JPanel tablePanel2 = new JPanel(new BorderLayout());
        JPanel buttonPanel2 = new JPanel(new FlowLayout());


        JButton deleteCar = new JButton("删除");
        deleteCar.addActionListener((e)->{
            Vector<Vector> vector2 = new Vector();
            vector2.addAll(vector);
            for (Vector vector1 : vector2) {
                if ((Boolean) vector1.get(0) == true){
                    vector.remove(vector1);
                    shoppingCartTable.setModel(new MyModel2());
                }
            }
        });
        JButton changeNum = new JButton("修改数量");
        changeNum.addActionListener((e)-> {
            int a = 0;
            for (Vector vector1 : vector) {
                if ((Boolean) vector1.get(0) == true){
                    modifyCarNum((String) vector1.get(2),vector,a);
                }
                a++;
            }

        });

        JButton buyit = new JButton("购买");
        buyit.addActionListener((e)->{
            Vector<Vector> vector2 = new Vector();
            vector2.addAll(vector);
            for (Vector vector1 : vector2) {
                if ((Boolean) vector1.get(0) == true){
                    Object id = vector1.get(1);
                    Object num = vector1.get(3);
                    try {
                       Integer id1 = (Integer) id;
                       Integer num1 = (Integer)num;
                       CarBuy(id1, num1,vector1);
                   }catch (RuntimeException e1){

                   }

                }
            }
        });
        buyit.addActionListener((e)->{

        });

        tablePanel2.add(shoppingCartTable.getTableHeader(),BorderLayout.NORTH);
        tablePanel2.add(shoppingCartTable,BorderLayout.CENTER);
        buttonPanel2.add(deleteCar);
        buttonPanel2.add(changeNum);
        buttonPanel2.add(buyit);
        panel2.add(tablePanel2,BorderLayout.CENTER);
        panel2.add(buttonPanel2,BorderLayout.SOUTH);










        JPanel panel3 = new JPanel(null);
        JLabel query = new JLabel("请输入要查询的订单的商品编号或会员编号");
        query.setForeground(Color.CYAN);
        query.setFont(new Font("黑体",0,30));
        query.setBounds(60,20,600,30);
        JLabel image = new JLabel(new ImageIcon("D:\\Java\\SM\\superShoppingSystem\\resources\\image2.jpg"));
        image.setBounds(80,80,500,400);
        JTextField input = new JTextField(16);
        input.setBounds(150,80,200,40);
        JButton button = new JButton("确定");
        button.addActionListener((e)->{
            Integer id = null;
            try {
                String idText = input.getText();
                id = new Integer(idText);
            }catch (NumberFormatException e1){
                id = 0;
            }
            b.query(id);
        });
        button.setBounds(350,80,100,40);
        panel3.add(query);
        panel3.add(input);
        panel3.add(image);
        panel3.add(button);




///排行榜
        JPanel panel4 = new JPanel(null){
            @Override
            protected void paintComponent(Graphics g) {
                ImageIcon icon = new ImageIcon("D:\\Java\\SM\\superShoppingSystem\\resources\\top5.jpg");
                Image img = icon.getImage();
                g.drawImage(img, 0, 0, icon.getIconWidth(), icon.getIconHeight(), icon.getImageObserver());
            }
        };
        panel4.setBackground(null);
        panel4.setOpaque(false);



        JPanel tablePanel = new JPanel();
        tablePanel.setBackground(null);
        tablePanel.setOpaque(false);
        JTable topTable = new JTable(new MyModel4());
        topTable.getTableHeader().setBounds(20,20,200,300);
        topTable.setBounds(20,30,200,300);
        JButton TopUpdatebutton = new JButton("更新");
        TopUpdatebutton.setBounds(270,300,100,40);
        TopUpdatebutton.addActionListener((e)->{
            topTable.setModel(new MyModel4());
        });

        tablePanel.add(topTable.getTableHeader());
        tablePanel.add(topTable);
        tablePanel.setBounds(170,50,300,300);
        panel4.add(tablePanel);
        panel4.add(TopUpdatebutton);










        tabbedPane.addTab("购买管理", panel1);
        tabbedPane.addTab("购物车", panel2);
        tabbedPane.addTab("订单查询", panel3);
        tabbedPane.addTab("商品排行榜", panel4);


        frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
        frame.getContentPane().add(topMainPanle,BorderLayout.NORTH);


        frame.setVisible(true);
    }


    private void browseHistory() {
        JFrame frame = new JFrame();
        //初始化
        Container contantPane = frame.getContentPane();
        frame.setResizable(false);//窗口大小不可变
        frame.setSize(500,500);
        frame.setTitle("浏览记录");
        frame.setLocationRelativeTo(null);
        frame.setBackground(Color.gray);
        JPanel tablePanel = new JPanel();
        JTable broHistoryTable = new JTable(new Mymodel3());
        JScrollPane js =new JScrollPane(broHistoryTable);
        JButton button = new JButton("确定");
        button.addActionListener((e)->{
            frame.dispose();
        });
        tablePanel.add(broHistoryTable.getTableHeader(),BorderLayout.NORTH);
        tablePanel.add(js,BorderLayout.CENTER);
        contantPane.add(tablePanel,BorderLayout.CENTER);
        contantPane.add(button,BorderLayout.SOUTH);
        frame.setVisible(true);
    }

    private class MyModel1 extends AbstractTableModel {
        Vector<String> colum = new Vector<>();
        Vector<Vector> good = g.updataItem();
        public MyModel1(){
            String[] columnNames = {"ID","商品名称","类型","数量","价格","状态","折扣","更新时间"};
            for (String columnName : columnNames) {
                colum.add(columnName);
            }
        }
        @Override
        public int getRowCount() {
            return good.size();
        }
        @Override
        public int getColumnCount() {
            return colum.size();
        }
        @Override
        public String getColumnName(int column){
            return colum.get(column);
        }
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return good.get(rowIndex).get(columnIndex);
        }
    }

    private class MyModel2 extends AbstractTableModel {
        Vector<String> colum = new Vector<>();
        public MyModel2(){
            String[] columnNames = {"选择","ID","商品名称","数量","价格","折扣"};
            for (String columnName : columnNames) {
                colum.add(columnName);
            }
        }
        Class[] typeArray = { Boolean.class,Integer.class, Object.class,
                Object.class,Object.class,Object.class };


        @Override
        public int getRowCount() {
            return vector.size();

        }

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

        @Override
        public String getColumnName(int column){
            return colum.get(column);
        }

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

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return true;
        }
        @Override
        public Class getColumnClass(int columnIndex) {
            return typeArray[columnIndex];// 返回每一列的数据类型
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            super.setValueAt(aValue, rowIndex, columnIndex);
        }
    }
    public void modifyCarNum(String name,Vector<Vector> vector,int rows){
        JFrame frame = new JFrame();
        //初始化
        Container contantPane = frame.getContentPane();
        frame.setResizable(false);//窗口大小不可变
        frame.setSize(300,150);
        frame.setTitle("修改数量");
        frame.setLocationRelativeTo(null);
        frame.setBackground(Color.gray);
        frame.setVisible(true);
        JPanel addPanel = new JPanel(null);
        // 1.商品数量
        JLabel Lable = new JLabel("输入"+name+"的数量: ");
        JTextField Text = new JTextField(4);
        Lable.setFont(new Font("黑体",0,15));
        Lable.setBounds(10,20,150,30);
        Text.setBounds(170,25,100,20);
        addPanel.add(Lable);
        addPanel.add(Text);
        JPanel YN = new JPanel();
        JButton yes = new JButton("确认修改");
        yes.addActionListener((e -> {
            try {
                String text = Text.getText();
                Integer num1 = new Integer(text);
                vector.get(rows).set(3,num1);
                shoppingCartTable.setModel(new MyModel2());
                frame.dispose();
            }catch (NumberFormatException e1){

            }


        }));
        JButton no = new JButton("取消");
        no.addActionListener((e )->{
            frame.dispose();
        } );
        YN.add(yes);
        YN.add(no);
        contantPane.add(YN,BorderLayout.SOUTH);
        contantPane.add(addPanel,BorderLayout.CENTER);
        frame.setVisible(true);
    }


    public boolean CarBuy(Integer id,Integer num,Vector vector)
    {
        entity.G g = null;
        try {
            g = DBulit.executeQueryByOne(entity.G.class, "select * from supermarket.goods where g_id = ?", id);
            $buyIt(g,num,vector);
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return false;
    }
    private void $buyIt(entity.G g, int num,Vector vector1) {
        JFrame frame = new JFrame();
        //初始化
        Container contantPane = frame.getContentPane();
        frame.setResizable(false);//窗口大小不可变
        frame.setSize(200,100);
        frame.setTitle("确认购买信息");
        frame.setLocationRelativeTo(null);
        frame.setBackground(Color.gray);
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JLabel message = new JLabel("确定要购买:"+num+"个"+g.getGName()+"吗");
        JButton button = new JButton("确定");
        button.addActionListener((e)->{
            if (num <= g.getGNum() ){
                b.payit(g,num);
                frame.dispose();
                vector.remove(vector1);
                shoppingCartTable.setModel(new MyModel2());
            }else {
                ResultGUI resultGUI =new ResultGUI(frame);
                resultGUI.Result("数量不足:",g.getGNum()-num);
            }
        });
        JButton button1 = new JButton("取消");
        button1.addActionListener((e)->{
            frame.dispose();
        });
        buttonPanel.add(button);
        buttonPanel.add(button1);
        contantPane.add(message,BorderLayout.CENTER);
        contantPane.add(buttonPanel,BorderLayout.SOUTH);
        frame.setVisible(true);
    }
/
    public void broswse(){
        JFrame frame = new JFrame();
        //初始化
        Container contantPane = frame.getContentPane();
        frame.setResizable(false);//窗口大小不可变
        frame.setSize(300,150);
        frame.setTitle("购买");
        frame.setLocationRelativeTo(null);
        frame.setBackground(Color.gray);
        frame.setVisible(true);
        JPanel addPanel = new JPanel(null);
        // 1.商品ID
        JLabel Lable = new JLabel("输入ID: ");
        JTextField Text = new JTextField(4);
        Lable.setFont(new Font("黑体",0,15));
        Lable.setBounds(10,20,100,30);
        Text.setBounds(80,25,150,20);
        //2.数量
        JLabel label2 = new JLabel("数量: ");
        JTextField text2 = new JTextField(4);
        label2.setFont(new Font("黑体",0,15));
        label2.setBounds(10,45,100,30);
        text2.setBounds(80,50,150,20);
        addPanel.add(Lable);
        addPanel.add(Text);
        addPanel.add(label2);
        addPanel.add(text2);
        //
        JPanel YN = new JPanel();
        JButton yes = new JButton("加入购物车");
        yes.addActionListener((e -> {
            Vector transientVictor = new Vector();
            Vector transientVictor2 = new Vector();
            entity.G g = null;
            Integer num = 0;
            try {
                String id1 = Text.getText();
                String num1 = text2.getText();
                num = new Integer(num1);
                Integer id = new Integer(id1);
                g = DBulit.executeQueryByOne(entity.G.class, "SELECT * FROM `supermarket`.`goods` where g_id=?", id);
            } catch (SQLException e1) {
                e1.printStackTrace();
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            } catch (InstantiationException e1) {
                e1.printStackTrace();
            } catch (NoSuchMethodException e1) {
                e1.printStackTrace();
            } catch (InvocationTargetException e1) {
                e1.printStackTrace();
            }catch (RuntimeException e1){
            }
            Integer id = new Integer(0);
            String string = new String("null");
            BigDecimal price= new BigDecimal("0");
            Float discount = new Float(0.0f);
            if (g != null){
                id = g.getGId();
                string = g.getGName();
                price = g.getGPrice();
                discount = g.getGDiscount();
            }
            transientVictor.add(new Boolean(false));
            transientVictor.add(id);
            transientVictor.add(string);
            transientVictor.add(num);
            transientVictor.add(price);
            transientVictor.add(discount);
            transientVictor2.add(id);
            transientVictor2.add(string);
            transientVictor2.add(price);
            transientVictor2.add(discount);
            vector2.add(transientVictor2);
            vector.add(transientVictor);
            shoppingCartTable.setModel(new MyModel2());
            frame.dispose();
        }));
        JButton no = new JButton("取消");
        no.addActionListener((e )->{
            Vector transientVictor2 = new Vector();
            entity.G g = null;
            try {
                String id1 = Text.getText();
                Integer id = new Integer(id1);
                g = DBulit.executeQueryByOne(entity.G.class, "SELECT * FROM `supermarket`.`goods` where g_id=?", id);
            } catch (SQLException e1) {
                e1.printStackTrace();
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            } catch (InstantiationException e1) {
                e1.printStackTrace();
            } catch (NoSuchMethodException e1) {
                e1.printStackTrace();
            } catch (InvocationTargetException e1) {
                e1.printStackTrace();
            }catch (RuntimeException e1){
            }
            Integer id = new Integer(0);
            String string = new String("null");
            BigDecimal price= new BigDecimal("0");
            Float discount = new Float(0.0f);
            if (g != null){
                id = g.getGId();
                string = g.getGName();
                price = g.getGPrice();
                discount = g.getGDiscount();
            }
            transientVictor2.add(id);
            transientVictor2.add(string);
            transientVictor2.add(price);
            transientVictor2.add(discount);
            vector2.add(transientVictor2);
            frame.dispose();
        } );
        YN.add(yes);
        YN.add(no);
        contantPane.add(YN,BorderLayout.SOUTH);
        contantPane.add(addPanel,BorderLayout.CENTER);
        frame.setVisible(true);
    }

    private class Mymodel3 extends AbstractTableModel{
        Vector<String> colum = new Vector<>();
        public Mymodel3(){
            String[] columnNames = {"ID","商品名称","价格","折扣"};
            for (String columnName : columnNames) {
                colum.add(columnName);
            }
        }

        @Override
        public int getRowCount() {
            return vector2.size();
        }

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

        @Override
        public String getColumnName(int column) {
            return colum.get(column);
        }

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

    private class MyModel4 extends AbstractTableModel {
        Vector<String> colum = new Vector<>();
        Vector<Vector> rows = b.Top();
        public MyModel4(){
            String[] columnNames = {"排名","ID","商品名称","销售量"};
            for (String columnName : columnNames) {
                colum.add(columnName);
            }
        }
        @Override
        public int getRowCount() {
            return rows.size();
        }

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

        @Override
        public String getColumnName(int column) {
            return colum.get(column);
        }

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

登录界面

```java
package controller;

import javax.swing.*;
import java.awt.*;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Objects;
import java.util.Properties;

/**
 * @ author Edward.wei
 * @date: 2021年04月03日11:03
 * @describtion:
 */
public class Login extends JFrame {
    private JLabel mainTile;
    private JLabel userNameLable;
    private JLabel passwordLable;
    private JLabel userNameLableCashier;
    private JLabel passwordLableCashier;
    private JButton logInButtonForManager;
    private JButton logInButtonForCashier;
    private JTextField userNameText;
    private JPasswordField passwordText;
    private JTextField userNameTextCashier;
    private JPasswordField passwordTextCashier;
    private JTabbedPane tabbedPane;
    public void logInGUI(){
        //初始化设置
        Container contantPane = getContentPane();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);//窗口大小不可变
        setSize(400,300);
        setTitle("\t\t\t超市管理系统");
        setBackground(Color.gray);
        //设置弹出窗口在屏幕中间(需先设置大小,在确定中间)
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());
        //提取密码信息
        Properties properties = new Properties();
        Properties propertiesForCashier = new Properties();
        try {
            properties.load(new FileReader("D:\\Java\\SM\\superShoppingSystem\\resources\\manager.properties"));
            propertiesForCashier.load(new FileReader("D:\\Java\\SM\\superShoppingSystem\\resources\\cashier.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //设置标签
        mainTile = new JLabel("超市管理系统");
        mainTile.setFont(new Font("黑体",2,30));
        mainTile.setForeground(Color.BLUE);
        //mainTile.setBounds(90,0,300,100);
        //设置卡片
        tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        JPanel managerPanel = new JPanel(null);
        JPanel cashierPanel = new JPanel(null);
        //设置输入框manager
        userNameLable = new JLabel("用户名: ");
        userNameLable.setFont(new Font("黑体",0,20));
        userNameLable.setBounds(50,20,100,50);
        passwordLable = new JLabel("密 码: ");
        passwordLable.setFont(new Font("黑体",0,20));
        passwordLable.setBounds(50,60,100,50);
        userNameText = new JTextField(10);
        userNameText.setBounds(120,30,200,30);
        passwordText = new JPasswordField(10);
        passwordText.setBounds(120,70,200,30);
        //设置输入框cashier
        userNameLableCashier = new JLabel("用户名: ");
        userNameLableCashier.setFont(new Font("黑体",0,20));
        userNameLableCashier.setBounds(50,20,100,50);
        passwordLableCashier = new JLabel("密 码: ");
        passwordLableCashier.setFont(new Font("黑体",0,20));
        passwordLableCashier.setBounds(50,60,100,50);
        userNameTextCashier = new JTextField(10);
        userNameTextCashier.setBounds(120,30,200,30);
        passwordTextCashier = new JPasswordField(10);
        passwordTextCashier.setBounds(120,70,200,30);
        //设置按钮
        logInButtonForManager = new JButton("管理员登录");
        logInButtonForManager.setBounds(150,150,100,35);
        logInButtonForManager.addActionListener((event)->{
            PageChange pageChange = new ManagerHomePage();
            logining(properties,pageChange,userNameText,passwordText);
        });
        //设置按钮cashier
        logInButtonForCashier = new JButton("收营员登录");
        logInButtonForCashier.setBounds(150,150,100,35);
        logInButtonForCashier.addActionListener((event)->{
            PageChange pageChange = new CashierHomePage();
            logining(propertiesForCashier,pageChange,userNameTextCashier,passwordTextCashier);
        });
        //添加主页面
        managerPanel.add(userNameLable);
        managerPanel.add(passwordLable);
        managerPanel.add(userNameText);
        managerPanel.add(passwordText);
        managerPanel.add(logInButtonForManager);
        cashierPanel.add(userNameLableCashier);
        cashierPanel.add(passwordLableCashier);
        cashierPanel.add(userNameTextCashier);
        cashierPanel.add(passwordTextCashier);
        cashierPanel.add(logInButtonForCashier);
        tabbedPane.add("管理员",managerPanel);
        tabbedPane.add("收银员",cashierPanel);
        contantPane.add(BorderLayout.NORTH,mainTile);
        contantPane.add(BorderLayout.CENTER,tabbedPane);
        setVisible(true);
    }
    private void logining(Properties properties,PageChange pageChange,JTextField userNameText,JTextField passwordText){
        System.out.println(userNameText.getText());
        System.out.println(passwordText.getText());
        if (!Objects.equals(userNameText.getText(),properties.getProperty("username"))
                || !Objects.equals(passwordText.getText(),properties.getProperty("password") )){
            //匿名内部类不作为参数写的话,则无法用lambed表达式,但是可以在花括号里在加一个花括号,即不用重写直接调方法
            new JDialog(){{
//                Image image = getToolkit().getImage("D:\\SM\\resources\\警告.jpeg");
                setIconImage(image);
                setTitle("警告");
                setModal(true);
                setLayout(null);
                setResizable(false);
                setSize(250,150);
                JLabel label = new JLabel("用户名或密码输入错误!");
                label.setBounds(10,50,250,20);
                label.setFont(new Font("黑体",2,20));
                label.setForeground(Color.RED);
                setLocationRelativeTo(null);
                add(label);
            }
            }.setVisible(true);
        }else {
            pageChange.homePage(userNameText.getText());
            dispose();
        }
    }


}
购买功能

```java
package controller;

import entity.*;
import entity.G;
import entity.GT;
import entity.Vip;
import service.GImpl;
import util.DBulit;

import javax.swing.*;
import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * @ author Edward.wei
 * @date: 2021年04月13日11:01
 * @describtion:
 */
public class Buy {
    MessageDigest messageDigest;
    GImpl ggg = new GImpl();
    public void buy(){
        JFrame frame = new JFrame();
        //初始化
        Container contantPane = frame.getContentPane();
        frame.setResizable(false);//窗口大小不可变
        frame.setSize(300,200);
        frame.setTitle("购买");
        frame.setLocationRelativeTo(null);
        frame.setBackground(Color.gray);
        frame.setVisible(true);
        JPanel addPanel = new JPanel(null);
        // 1.商品ID
        JLabel Lable = new JLabel("输入ID: ");
        JTextField Text = new JTextField(4);
        Lable.setFont(new Font("黑体",0,15));
        Lable.setBounds(10,20,100,30);
        Text.setBounds(80,25,150,20);
        // 2.数量
        JLabel numLable = new JLabel("数\t\t量: ");
        JTextField numText = new JTextField(6);
        numLable.setFont(new Font("黑体",0,15));
        numLable.setBounds(10,40,100,30);
        numText.setBounds(80,45,150,20);
        addPanel.add(Lable);
        addPanel.add(Text);
        addPanel.add(numLable);
        addPanel.add(numText);
        JPanel YN = new JPanel();
        JButton yes = new JButton("确定");
        yes.addActionListener((e -> {
            Integer id = null;
            Integer num = null;
            G g = null;
            try{
                String id1 = Text.getText();
                String num1 = numText.getText();
                id = new Integer(id1);
                num = new Integer(num1);
            }catch (NumberFormatException e1){
                id = 0;
                num = 0;
            }
            try {
                g = DBulit.executeQueryByOne(G.class, "select * from supermarket.goods where g_id = ?", id);
            } catch (SQLException e1) {
                e1.printStackTrace();
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            } catch (InstantiationException e1) {
                e1.printStackTrace();
            } catch (NoSuchMethodException e1) {
                e1.printStackTrace();
            } catch (InvocationTargetException e1) {
                e1.printStackTrace();
            }
            if (g == null || g.getGName() == null && g.getGNum() == null){
                ResultGUI resultGUI = new ResultGUI(frame);
                resultGUI.Result("id有误",0);
            }else {
                $buyIt(g,num);
                frame.dispose();
            }


        }));
        JButton no = new JButton("取消");
        no.addActionListener((e )->{
            frame.dispose();
        } );
        YN.add(yes);
        YN.add(no);
        contantPane.add(YN,BorderLayout.SOUTH);
        contantPane.add(addPanel,BorderLayout.CENTER);
        frame.setVisible(true);
    }

    private void $buyIt(G g,int num) {
        JFrame frame = new JFrame();
        //初始化
        Container contantPane = frame.getContentPane();
        frame.setResizable(false);//窗口大小不可变
        frame.setSize(200,100);
        frame.setTitle("确认购买信息");
        frame.setLocationRelativeTo(null);
        frame.setBackground(Color.gray);
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JLabel message = new JLabel("确定要购买:"+num+"个"+g.getGName()+"吗");
        JButton button = new JButton("确定");
        button.addActionListener((e)->{
            if (num <= g.getGNum() ){
                payit(g,num);
                frame.dispose();
            }else {
                ResultGUI resultGUI =new ResultGUI(frame);
                resultGUI.Result("数量不足:",g.getGNum()-num);
            }
        });
        JButton button1 = new JButton("取消");
        button1.addActionListener((e)->{
            frame.dispose();
        });
        buttonPanel.add(button);
        buttonPanel.add(button1);
        contantPane.add(message,BorderLayout.CENTER);
        contantPane.add(buttonPanel,BorderLayout.SOUTH);
        frame.setVisible(true);
    }

    public void payit(G g, int num) {
        JFrame frame = new JFrame();
        //初始化
        Container contantPane = frame.getContentPane();
        frame.setResizable(false);//窗口大小不可变
        frame.setSize(300,150);
        frame.setTitle("会员验证");
        frame.setLocationRelativeTo(null);
        frame.setBackground(Color.gray);
        JPanel addPanel = new JPanel();
        //输入会员id
        JLabel Lable = new JLabel("输入ID: ");
        JTextField Text = new JTextField(4);
        Lable.setFont(new Font("黑体",0,15));
        Lable.setBounds(10,20,100,30);
        Text.setBounds(80,25,150,20);
        // 2.密码
        JLabel passLable = new JLabel("密\t\t码: ");
        JPasswordField passText = new JPasswordField(6);
        passLable.setFont(new Font("黑体",0,15));
        passLable.setBounds(10,40,100,30);
        passText.setBounds(80,45,150,20);
        addPanel.add(Lable);
        addPanel.add(Text);
        addPanel.add(passLable);
        addPanel.add(passText);
        JPanel YN = new JPanel();
        JButton yes = new JButton("确定");
        yes.addActionListener((e -> {
            String s = null;
            Integer id = null;
            Vip vip = null;
            //id转为数字
            try{
                String id1 = Text.getText();
                id = new Integer(id1);
            }catch (NumberFormatException e1){
                id = 0;
            }
            //将id查询返回用户对象
            try {
                vip = DBulit.executeQueryByOne(entity.Vip.class, "select * from supermarket.vip where v_id = ?", id);
            } catch (SQLException e1) {
                e1.printStackTrace();
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            } catch (InstantiationException e1) {
                e1.printStackTrace();
            } catch (NoSuchMethodException e1) {
                e1.printStackTrace();
            } catch (InvocationTargetException e1) {
                e1.printStackTrace();
            }
            //加密密码
            try {
                messageDigest = MessageDigest.getInstance("MD5");
                messageDigest.update(passText.getText().getBytes());
                BigInteger bigInteger = new BigInteger(1,messageDigest.digest());
                String pass1 = bigInteger.toString(16);
                s = bigInteger.toString(16);

            } catch (NoSuchAlgorithmException e1) {
                e1.printStackTrace();
            }
            //用加密后的密码与用户密码比对
            if(Objects.deepEquals(vip.getVPass(),s)){
                choiceWayToPay(g,vip,num);
                frame.dispose();
            }else {
                ResultGUI resultGUI = new ResultGUI(frame);
                resultGUI.Result("用户或密码错误",0);
            }
        }));
        JButton no = new JButton("取消");
        no.addActionListener((e )->{
            frame.dispose();
        } );
        YN.add(yes);
        YN.add(no);
        contantPane.add(YN,BorderLayout.SOUTH);
        contantPane.add(addPanel,BorderLayout.CENTER);
        frame.setVisible(true);
    }

    private void choiceWayToPay(G g, Vip vip, int num) {
        JFrame frame = new JFrame();
        //初始化
        Container contantPane = frame.getContentPane();
        frame.setResizable(false);//窗口大小不可变
        frame.setSize(300,150);
        frame.setTitle("支付方式选择");
        frame.setLocationRelativeTo(null);
        frame.setBackground(Color.gray);
        JPanel addPanel = new JPanel(null);
        JLabel balance = new JLabel("您的余额为:"+vip.getVBalance());
        balance.setBounds(10,10,200,30);
        JComboBox<String> payWay = new JComboBox<>();
        payWay.addItem("现金支付");
        payWay.addItem("余额支付");
        payWay.setBounds(20,40,150,30);
        addPanel.add(balance);
        addPanel.add(payWay);
        JPanel YN = new JPanel();
        JButton yes = new JButton("确定");
        yes.addActionListener((e -> {
           if(payWay.getSelectedIndex() == 0){
               int i = madeOrder(g, vip, num, 0);
               ResultGUI resultGUI = new ResultGUI(frame);
               resultGUI.Result("影响结果",i);
               frame.dispose();
           }else {
               BigDecimal gNum = new BigDecimal(num);
               BigDecimal totalPrice = g.getGPrice().multiply(gNum);
               if (totalPrice.compareTo(vip.getVBalance()) == 1){
                   ResultGUI resultGUI = new ResultGUI(frame);
                   resultGUI.Result("余额不足",0);
               }else {
                   int i = madeOrder(g, vip, num, 1);
                   ResultGUI resultGUI = new ResultGUI(frame);
                   resultGUI.Result("影响结果",i);
                   frame.dispose();
               }
           }
        }));
        JButton no = new JButton("取消");
        no.addActionListener((e )->{
            frame.dispose();
        } );
        YN.add(yes);
        YN.add(no);
        contantPane.add(YN,BorderLayout.SOUTH);
        contantPane.add(addPanel,BorderLayout.CENTER);
        frame.setVisible(true);
    }

    private int madeOrder(G g, Vip vip, int num,Integer payWay) {
        SimpleDateFormat data = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int result = 0;
        BigDecimal gNum = new BigDecimal(num);
        BigDecimal gDiscount = new BigDecimal(g.getGDiscount());
        BigDecimal $10 = new BigDecimal(10);
        BigDecimal totalPrice = (g.getGPrice().multiply(gNum)).multiply(gDiscount.divide($10));
        String date = data.format(System.currentTimeMillis());
        try {
            //2.生成订单信息以及详细详细
            int i1 = DBulit.executeUpdata("INSERT INTO `supermarket`.`o_information`(`o_vip_id`, `o_money`, `o_pay_way`,`o_time`) VALUES (?, ?, ?,?)"
                    ,vip.getVId(),totalPrice,payWay,date);
            result+= i1;
            OrderInfor orderInfor = DBulit.executeQueryByOne(OrderInfor.class, "select * from `supermarket`.`o_information` where o_time = ?"
                    ,date);
            //问题:只要点余额支付,该信息就为空
            //Timestamp会产生3位数的毫秒值,而datetime会四舍五入,这就导致了查询不到信息
            //
            int i2 = DBulit.executeUpdata("INSERT INTO `supermarket`.`o_more_information`(`o_id`, `g_id`,`g_num`) VALUES (?, ?, ?)"
                    ,orderInfor.getOId(),g.getGId(),num);
            result+=i2;
            //1,减少该商品的数量
            g.setGNum(g.getGNum()-num);
            int i = ggg.modifyItem(g, g.getGId());
            result +=i;
            //3.扣会员余额,加积分
            if (payWay == 0){
                //只加积分
                int i3 = DBulit.executeUpdata("UPDATE `supermarket`.`vip` SET `v_score` = ? WHERE `v_id` = ?"
                        , vip.getVScore() + 100, vip.getVId());
                result+=i3;
            }else {
                int i3 = DBulit.executeUpdata("UPDATE `supermarket`.`vip` SET `v_balance` = ? WHERE `v_id` = ?"
                        , vip.getVBalance().subtract(totalPrice), vip.getVId());
                result+=i3;
                int i4 = DBulit.executeUpdata("UPDATE `supermarket`.`vip` SET `v_score` = ? WHERE `v_id` = ?"
                        , vip.getVScore() + 100, vip.getVId());
                result+=i4;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return result;
    }



    public void query(Integer id){
        JFrame frame = new JFrame();
        //初始化
        Container contantPane = frame.getContentPane();
        frame.setResizable(false);//窗口大小不可变
        frame.setSize(500,500);
        frame.setTitle("查询");
        frame.setLocationRelativeTo(null);
        frame.setBackground(Color.gray);
        JPanel tablePanel = new JPanel();
        Vector<String> colum = new Vector<>();
        Vector<Vector> vectors = new Vector<>();
        String[] columnNames = {"订单ID","vip","交易额","交易方式","商品id","交易数量","交易时间"};
        for (String columnName : columnNames) {
            colum.add(columnName); }
        try {
            Vector vector = new Vector();
            List<Order> orderList = DBulit.executeQuery(Order.class, "SELECT oi.o_id,oi.o_vip_id,oi.o_money,oi.o_pay_way,omi.g_id,omi.g_num,oi.o_time FROM o_information oi INNER JOIN o_more_information omi ON oi.o_id = omi.o_id WHERE oi.o_vip_id = ? OR omi.g_id = ?;"
                    , id,id);
            vector.addAll(orderList);
            Iterator iterator = vector.iterator();
            while (iterator.hasNext())
            {
                Object o = iterator.next();
                Vector vector1 = new Vector();
                if (o instanceof entity.Order)
                {
                    vector1.add(((entity.Order) o).getOId());
                    vector1.add(((entity.Order) o).getOVipId());
                    vector1.add(((entity.Order) o).getOMoney());
                    vector1.add(((entity.Order) o).getOPayWay());
                    vector1.add(((entity.Order) o).getGId());
                    vector1.add(((entity.Order) o).getGNum());
                    vector1.add(((Order) o).getOTime());
                }
                vectors.add(vector1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        JTable table = new JTable(vectors,colum);
        JScrollPane js = new JScrollPane(table);
        tablePanel.add(table.getTableHeader(),BorderLayout.NORTH);
        tablePanel.add(js,BorderLayout.CENTER);
        contantPane.add(tablePanel);
        frame.setVisible(true);
    }

    public Vector<Vector> Top(){
        try {
            Vector<Vector> vectors = new Vector<>();
            Vector vector = new Vector<>();
            List<Top> tops = DBulit.executeQuery(Top.class,
                    "SELECT  omi.g_id,g.g_name, SUM(omi.g_num) g_sum FROM supermarket.o_more_information omi INNER JOIN supermarket.goods g ON omi.g_id = g.g_id GROUP BY omi.g_id ORDER BY SUM(omi.g_num) DESC LIMIT 10;");
            vector.addAll(tops);
            Iterator iterator = vector.iterator();
            Integer a = 0;
            String[] ccc = {"第一名","第二名","第三名","第四名","第五名","第六名","第七名","第八名","第九名","第十名"};
            while (iterator.hasNext())
            {
                Object o = iterator.next();
                Vector vector1 = new Vector();
                if (o instanceof entity.Top)
                {
                    vector1.add(ccc[a]);
                    vector1.add(((entity.Top) o).getGId());
                    vector1.add(((entity.Top) o).getGName());
                    vector1.add(((entity.Top) o).getGSum());

                }
                vectors.add(vector1);
                a++;
            }
            return vectors;
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;

    }





}



数据库工具类

```java
package util;

import com.mysql.jdbc.Driver;
import common.KeyNotFound;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.io.IOException;
import java.util.*;

/**
 * @ author Edward.wei
 * @date: 2021年04月09日10:11
 * @describtion:
 */
public class DBulit
{
    private static Properties properties;
    static
    {//保证该对象每次运行只new一次
        properties = new Properties();
        try {
            properties.load(DBulit.class.getClassLoader().getResourceAsStream("DBconn.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static Connection getConnection() throws ClassNotFoundException, SQLException {
            Class.forName(getValue("driver"));//获得driver实例,同意由driverManager调用
            Connection connection = DriverManager.getConnection(getValue("url"),getValue("username"),getValue("password"));
            return connection;//获取连接对象并返回给调用者
    }

    private static String getValue(String key)
    {//用properties获得文件里的参数,方便在文件里更改
        if (properties.containsKey(key))
        {
            return properties.getProperty(key);
        }else
        {
            throw new KeyNotFound("key没找到");
        }

    }
    /**
     * describtion: 可以执行 增加,删除,修改数据的操作
     * */
    public static int executeUpdata(String sql,Object... param) throws SQLException, ClassNotFoundException {
        Connection conn = getConnection();//接受连接对象
        PreparedStatement preparedStatement = conn.prepareStatement(sql);//返回prepareStatement对象并预编译了sql语句
        if(param.length > 0)
        {//如果有占位符,把占位符的参数填上
            for (int i = 0; i < param.length; i++)
            {
                preparedStatement.setObject(i+1,param[i]);

            }
        }
        int i = preparedStatement.executeUpdate();//执行语句并返回影响了几行
        return i;
    }

    public static <T> List<T> executeQuery(Class<T> class1,String sql,Object...param ) throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Connection conn = getConnection();//接受连接对象
        PreparedStatement preparedStatement = conn.prepareStatement(sql);//返回prepareStatement对象并预编译了sql语句
        if(param.length > 0)
        {//如果有占位符,把占位符的参数填上
            for (int i = 0; i < param.length; i++)
            {
                preparedStatement.setObject(i+1,param[i]);

            }
        }
        ResultSet resultSet = preparedStatement.executeQuery();//已经查到数据返回给一个结果集
        //以下是处理这个结果集,变成想要的类型
        int classLength = class1.getDeclaredFields().length;
        List<T> list = new Vector<>();
        while (resultSet.next()){//如同迭代器,一行一行的迭代
            //造对象放到列表里
            T t = class1.newInstance();
            for (int i = 0; i < classLength; i++) {
                //利用set方法拼接字符串来通过反射调用 局限性:假定构造方法和数据库表名都是按照规定起的
                StringBuffer setMethod = new StringBuffer("set");
                String columnLabel = resultSet.getMetaData().getColumnLabel(i + 1);//取该列表字段表字段
                String[] lableArray = columnLabel.split("_");//有下划线的都给分割
                for (String s : lableArray) {//如果有下划线的就是多个元素(词),没下划线的就是一个元素
                    setMethod.append(s.substring(0,1).toUpperCase()+s.substring(1));//每个词首字母大写然后拼接
                }
                Class<?> aClass = Class.forName(resultSet.getMetaData().getColumnClassName(i + 1));
                Method method = class1.getMethod(setMethod.toString(),aClass);
                method.invoke(t,resultSet.getObject(i+1));
            }
            list.add(t);
        }
        return list;
    }

    public static<T> T executeQueryByOne(Class<T> class1, String sql,Object...param) throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException
    {
        Connection conn = getConnection();//接受连接对象
        PreparedStatement preparedStatement = conn.prepareStatement(sql);//返回prepareStatement对象并预编译了sql语句
        if(param.length > 0)
        {//如果有占位符,把占位符的参数填上
            for (int i = 0; i < param.length; i++)
            {
                preparedStatement.setObject(i+1,param[i]);

            }
        }
        ResultSet resultSet = preparedStatement.executeQuery();//已经查到数据返回给一个结果集
        //以下是处理这个结果集,变成想要的类型
        int classLength = class1.getDeclaredFields().length;
            //造对象放到列表里
         T t = class1.newInstance();
         while (resultSet.next()){
        for (int i = 0; i < classLength; i++)
        {
            //利用set方法拼接字符串来通过反射调用 局限性:假定构造方法和数据库表名都是按照规定起的
            StringBuffer setMethod = new StringBuffer("set");
            String columnLabel = resultSet.getMetaData().getColumnLabel(i + 1);//取该列表字段表字段
            String[] lableArray = columnLabel.split("_");//有下划线的都给分割
            for (String s : lableArray)
            {//如果有下划线的就是多个元素(词),没下划线的就是一个元素
                setMethod.append(s.substring(0,1).toUpperCase()+s.substring(1));//每个词首字母大写然后拼接
            }
            //获取方法类对象
            Class<?> aClass = Class.forName(resultSet.getMetaData().getColumnClassName(i + 1));
            Method method = class1.getMethod(setMethod.toString(),aClass);
            method.invoke(t,resultSet.getObject(i+1));
        }}
        return t;
    }
}







你可能感兴趣的:(java,mysql,sql)