Java超市收银系统(八、数据导入)

引言

        当选择1时,程序读取 “商品信息.xls” 文件,将所有数据存放于product集合中,然后将集合中的所有数据增加到商品表中,增加的时候要检查每条记录的条形码在商品表中是否存在,若存在,则不需要增加到数据库中,所有数据增加完毕后,显示“成功从excel文件导入XXX条商品数据”,返回子菜单。

        当选择2时,程序读取 “商品信息.xls” 文件,将所有数据存放于product集合中,然后将集合中的所有数据增加到商品表中,增加的时候要检查每条记录的条形码在商品表中是否存在,若存在,则不需要增加。

功能实现

第三方库导入

        jxl包导入,用于实现对excel处理。从Maven仓库中下载jar文件,之前的数据库连接mysql同样如此,也要下载jar包。Maven仓库链接如下:

​​​​​​Maven Repository: Search/Browse/Explore (mvnrepository.com)

在搜索栏搜索mysql和jxl:

点击合适版本进入,点击jar自动下载对应包:

将jar添加到idea编译器中,最后点击OK:

导入功能

        ok,相信前面博客的dao、vo、util已经讲的很明白了,我们重点来看ui中Driver函数的实现。

public static void main(String[] args) {
    while(true) {
        System.out.println("===****超市商品管理维护====");
        System.out.println("1、从excel中导入数据");
        System.out.println("2、从文本文件导入数据");
        System.out.println("3、返回主菜单");
        System.out.println("请选择(1-3):");
        Scanner scanner = new Scanner(System.in);
        int choice = scanner.nextInt();
        switch (choice) {
            case 1:
                inputExcel();
                break;
            case 2:
                inputTxt();
                break;
            case 3:
                System.out.println("返回主菜单");
                break;
            default:
                System.out.println("错误");
        }
    }
}
  • 这个方法在一个无限循环中显示菜单,让用户选择要执行的操作。
  • 根据用户的选择,程序调用不同的方法来处理数据导入。
private static void inputExcel() {
    File file = new File("D:\\1111111111111111111111111\\数据导入\\excel\\商品信息.xls");
    List<Product> productList = new ArrayList<>();

    try {
        FileInputStream fis = new FileInputStream(file);
        Workbook workbook = Workbook.getWorkbook(fis);

        // 获取第一个工作表
        Sheet sheet = workbook.getSheet(0);

        // 循环访问行
        for (int i = 1; i < sheet.getRows(); i++) { // 跳过表头(假设第一行是表头)
            String barCode = sheet.getCell(0, i).getContents();
            String productName = sheet.getCell(1, i).getContents();
            String priceStr = sheet.getCell(2, i).getContents(); // 读取价格字符串
            String supply = sheet.getCell(3, i).getContents();

            float price;
            try {
                price = Float.parseFloat(priceStr);
            } catch (NumberFormatException e) {
                System.err.println("发现无效的价格数据:" + priceStr);
                continue; // 跳过无效的数据行
            }

            // 检查具有相同条形码的产品是否已存在
            Product existingProduct = ProductDAO.queryByBarcode(barCode);
            if (existingProduct == null) {
                Product product = new Product(barCode, productName, price, supply);
                productList.add(product);
            }
        }

        // 将产品插入数据库
        int count = 0;
        for (Product product : productList) {
            boolean success = ProductDAO.insert(product);
            if (success) {
                count++;
            }
        }

        System.out.println("成功插入了 " + count + " 个产品到数据库中。");

    } catch (IOException | BiffException e) {
        e.printStackTrace();
    }
}
  • 该方法从指定路径的Excel文件中读取数据。
  • 跳过表头(第一行是表头),然后逐行读取商品信息。
  • 解析价格并检查商品是否已存在数据库中,如果不存在,则将商品信息添加到产品列表中。
  • 最后,将产品列表中的商品信息插入数据库,并显示成功插入的数量。

 

private static void inputTxt() {
    List<Product> productList = new ArrayList<>();
    String filePath = "D:\\1111111111111111111111111\\数据导入\\txt\\商品信息.txt";

    try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {

        // 读取并丢弃前两行
        String line = reader.readLine(); // 第一行
        if (line != null) {
            line = reader.readLine(); // 第二行
        }

        while ((line = reader.readLine()) != null) {
            String[] parts = line.split("\t"); // 使用制表符作为分隔符
            if (parts.length == 4) {
                String barCode = parts[0];
                String productName = parts[1];
                String price = parts[2];
                String supply = parts[3];

                // 检查条形码是否已存在
                if (ProductDAO.queryByBarcode(barCode) == null) {
                    Product product = new Product(barCode, productName, Float.parseFloat(price), supply);
                    productList.add(product);
                }
            } else {
                System.out.println("文本文件格式错误:" + line);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("无法读取文本文件", e);
    }

    // 将 productList 中的商品信息插入数据库
    int successfulInsertions = 0;
    for (Product product : productList) {
        if (ProductDAO.insert(product)) { // 插入商品信息
            successfulInsertions++;
        }
    }

    System.out.println("成功从文本文件导入 " + successfulInsertions + " 条商品数据");
}
  • 该方法从指定路径的文本文件中读取数据。
  • 跳过前两行,然后逐行读取商品信息。
  • 根据制表符(\t)分隔字段,并检查商品是否已存在数据库中,如果不存在,则将商品信息添加到产品列表中。
  • 最后,将产品列表中的商品信息插入数据库,并显示成功导入的数量。

        这个程序提供了一个命令行界面,通过选择菜单选项,用户可以从Excel或文本文件中导入商品数据,并将数据插入到数据库中。它包含了基本的错误处理和数据验证,以确保导入过程的正确性。 

结果展示

相关导入excel和txt文件如下:

导入前数据库:

 导入后数据库更新:

完整代码

ui—Driver

package ui;

import dao.ProductDAO;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import vo.Product;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Driver {
    public static void main(String[] args) {
        while(true) {
            System.out.println("===****超市商品管理维护====");
            System.out.println("1、从excel中导入数据");
            System.out.println("2、从文本文件导入数据");
            System.out.println("3、返回主菜单");
            System.out.println("请选择(1-3):");
            Scanner scanner = new Scanner(System.in);
            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    inputExcel();
                    break;
                case 2:
                    inputTxt();
                    break;
                case 3:
                    System.out.println("返回主菜单");
                    break;
                default:
                    System.out.println("错误");

            }
        }
    }

    private static void inputExcel() {
        //Scanner scanner = new Scanner(System.in);
        //System.out.println("请输入要导入的 Excel 文件路径:");
        //String filePath = scanner.nextLine();
        File file = new File("D:\\1111111111111111111111111\\数据导入\\excel\\商品信息.xls");
        List<Product> productList = new ArrayList<>();

        try {
            FileInputStream fis = new FileInputStream(file);
             Workbook workbook = Workbook.getWorkbook(fis);

            // 获取第一个工作表
            Sheet sheet = workbook.getSheet(0);

            // 循环访问行
            for (int i = 1; i < sheet.getRows(); i++) { // 跳过表头(假设第一行是表头)
                String barCode = sheet.getCell(0, i).getContents();
                String productName = sheet.getCell(1, i).getContents();
                String priceStr = sheet.getCell(2, i).getContents(); // 读取价格字符串
                String supply = sheet.getCell(3, i).getContents();

                float price;
                try {
                    price = Float.parseFloat(priceStr);
                } catch (NumberFormatException e) {
                    System.err.println("发现无效的价格数据:" + priceStr);
                    continue; // 跳过无效的数据行
                }

                // 检查具有相同条形码的产品是否已存在
                Product existingProduct = ProductDAO.queryByBarcode(barCode);
                if (existingProduct == null) {
                    Product product = new Product(barCode, productName, price, supply);
                    productList.add(product);
                }
            }

            // 将产品插入数据库
            int count = 0;
            for (Product product : productList) {
                boolean success = ProductDAO.insert(product);
                if (success) {
                    count++;
                }
            }

            System.out.println("成功插入了 " + count + " 个产品到数据库中。");

        } catch (IOException | BiffException e) {
            e.printStackTrace();
        }
    }

    private static void inputTxt() {
        List<Product> productList = new ArrayList<>();
        String filePath = "D:\\1111111111111111111111111\\数据导入\\txt\\商品信息.txt";

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {

            // 读取并丢弃前两行
            String line = reader.readLine(); // 第一行
            if (line != null) {
                line = reader.readLine(); // 第二行
            }

            while ((line = reader.readLine()) != null) {
                String[] parts = line.split("\t"); // 使用制表符作为分隔符
                if (parts.length == 4) {
                    String barCode = parts[0];
                    String productName = parts[1];
                    String price = parts[2];
                    String supply = parts[3];

                    // 检查条形码是否已存在
                    if (ProductDAO.queryByBarcode(barCode) == null) {
                        Product product = new Product(barCode, productName, Float.parseFloat(price), supply);
                        productList.add(product);
                    }
                } else {
                    System.out.println("文本文件格式错误:" + line);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("无法读取文本文件", e);
        }

        // 将 productList 中的商品信息插入数据库
        int successfulInsertions = 0;
        for (Product product : productList) {
            if (ProductDAO.insert(product)) { // 插入商品信息
                successfulInsertions++;
            }
        }

        System.out.println("成功从文本文件导入 " + successfulInsertions + " 条商品数据");
    }
}

vo—Product

package vo;

public class Product {
    private String barCode;
    private String productName;
    private float price;
    private String supply;

    public Product() {
    }

    public Product(String barCode, String productName, float price, String supply) {
        this.barCode = barCode;
        this.productName = productName;
        this.price = price;
        this.supply = supply;
    }

    public String getBarCode() {
        return barCode;
    }

    public void setBarCode(String barCode) {
        this.barCode = barCode;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public String getSupply() {
        return supply;
    }

    public void setSupply(String supply) {
        this.supply = supply;
    }
}

dao—ProductDAO

package dao;

import util.DBUtil;
import vo.Product;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ProductDAO {
    public static Product queryByBarcode(String barcode) {
        Connection con = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        Product product = null;
        try {
            con = DBUtil.getConnection();
            String sql = "SELECT * FROM t_shangping WHERE tiaoma = ?";
            pst = con.prepareStatement(sql);
            pst.setString(1, barcode);
            rs = pst.executeQuery();
            if (rs.next()) {
                product = new Product();
                product.setBarCode(rs.getString("tiaoma"));
                product.setProductName(rs.getString("mingcheng"));
                product.setPrice(rs.getFloat("danjia"));
                product.setSupply(rs.getString("gongyingshang"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(con, pst);
        }
        return product;
    }

    public static boolean insert(Product product) {
        Connection con = null;
        PreparedStatement pst = null;
        boolean success = false;
        try {
            con = DBUtil.getConnection();
            String sql = "INSERT INTO t_shangping (tiaoma, mingcheng, danjia, gongyingshang) VALUES (?, ?, ?, ?)";
            pst = con.prepareStatement(sql);
            pst.setString(1, product.getBarCode());
            pst.setString(2, product.getProductName());
            pst.setFloat(3, product.getPrice());
            pst.setString(4, product.getSupply());
            int rowsAffected = pst.executeUpdate();
            if (rowsAffected > 0) {
                success = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(con, pst);
        }
        return success;
    }

}

util—DBUtil

package util;

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

public class DBUtil {

    //驱动加载,只需执行一次
    static{
        String driveName = "com.mysql.cj.jdbc.Driver";
        try {
            Class.forName(driveName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    //获取链接
    public static Connection getConnection(){
        String url = "jdbc:mysql://localhost:3306/sale?useUnicode=true&characterEncoding=utf-8";
        String user = "root";
        String password = "123456";
        Connection con = null;
        try {
            con = DriverManager.getConnection(url,user,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return con;
    }

    //关闭资源
    public static void close(Connection con, PreparedStatement pst){
        if(con!=null) {
            try {
                con.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(pst!=null) {
            try {
                pst.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

}

mysql

/*
Navicat MySQL Data Transfer
 
Source Server         : localhost_3306
Source Server Version : 80032
Source Host           : localhost:3306
Source Database       : xiaoshou
 
Target Server Type    : MYSQL
Target Server Version : 80032
File Encoding         : 65001
 
Date: 2023-05-11 10:27:07
*/
 
SET FOREIGN_KEY_CHECKS=0;
use sale;
-- ----------------------------
-- Table structure for t_shangping
-- ----------------------------
DROP TABLE IF EXISTS `t_shangping`;
CREATE TABLE `t_shangping` (
  `tiaoma` varchar(255) NOT NULL,
  `mingcheng` varchar(255) DEFAULT NULL,
  `danjia` decimal(10,2) DEFAULT NULL,
  `gongyingshang` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`tiaoma`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
select * from t_shangping;
 
-- ----------------------------
-- Records of t_shangping
-- ----------------------------
INSERT INTO `t_shangping` VALUES ('100001', '手机', '4500.00', '华为');
INSERT INTO `t_shangping` VALUES ('100002', '鼠标', '61.00', '华为');
INSERT INTO `t_shangping` VALUES ('100003', '矿泉水', '2.50', '农夫山泉');
INSERT INTO `t_shangping` VALUES ('100004', '香烟', '20.00', '武汉卷烟厂');
INSERT INTO `t_shangping` VALUES ('100005', '牙膏', '4.50', '中华牙膏厂');
INSERT INTO `t_shangping` VALUES ('200001', '电脑', '4300.00', 'dell');
INSERT INTO `t_shangping` VALUES ('200002', '小明同学', '5.50', '武汉饮料集团');
 
-- ----------------------------
-- Table structure for t_shouyinmingxi
-- ----------------------------
DROP TABLE IF EXISTS `t_shouyinmingxi`;
CREATE TABLE `t_shouyinmingxi` (
  `liushuihao` varchar(255) NOT NULL,
  `tiaoma` varchar(255) DEFAULT NULL,
  `mingcheng` varchar(255) DEFAULT NULL,
  `danjia` decimal(10,0) DEFAULT NULL,
  `shuliang` int DEFAULT NULL,
  `shouyinyuan` varchar(255) DEFAULT NULL,
  `xiaoshoushijian` datetime DEFAULT NULL,
  PRIMARY KEY (`liushuihao`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
select * from t_shouyinmingxi;
-- ----------------------------
-- Records of t_shouyinmingxi
-- ----------------------------
 
-- ----------------------------
-- Table structure for t_yonghu
-- ----------------------------
DROP TABLE IF EXISTS `t_yonghu`;
CREATE TABLE `t_yonghu` (
  `yonghuming` varchar(255) NOT NULL,
  `mima` varchar(255) DEFAULT NULL,
  `xingming` varchar(255) DEFAULT NULL,
  `juese` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`yonghuming`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
select * from t_yonghu;
-- ----------------------------
-- Records of t_yonghu
-- ----------------------------
INSERT INTO `t_yonghu` VALUES ('mk', 'mk123', '明空', '管理员');
INSERT INTO `t_yonghu` VALUES ('jx', 'jx123', '瑾熙', '收银员');

相关其他功能实现请参考前面的博客

Java超市收银系统(一、用户登录)_java商超收银系统-CSDN博客

Java超市收银系统(二、用户权限)-CSDN博客

Java超市收银系统(三、密码修改)-CSDN博客

Java超市收银系统(四、收银功能)_java超市系统-CSDN博客

Java超市收银系统(五、收银统计)-CSDN博客

Java超市收银系统(六、商品增加和修改)-CSDN博客

Java超市收银系统(七、商品修改和删除)-CSDN博客

  • 14
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值