根据文件的下一行插入或更新数据库

时间:2017-05-30 16:08:09

标签: java mysql sql jdbc java.util.scanner

我有一个文本文件:

enter image description here

其中包含与书籍顺序相关的信息,其中单个订单可以包含一本或多本书籍的多个副本。

我想计算客户在单个订单中花费的总金额,因此订单中每个ISBN的numCopies * bookPrice。第一个订单是(1 * 15.99)= 15.99。第二个(10 * 11.99 + 20 * 14.99)= 419.70。第三次(1 * 15.99)。

我正在浏览带有扫描仪的文本文件,在我继续浏览时将文本文件的元素添加到文本文件中。为了计算订单总数,我试图累计每行的成本,其中一行出现在一行上,直到达到orderNum更改的行。然后将总订单金额插入数据库。

我不确定我是否可以正确检查何时应该下达订单总额并重置下一个订单号并将此总数插入数据库。或者基本上计算总数,然后在读完所有订单数据后更新数据库。

相关代码:

class TestConnect {
    static final String DROP_TABLE_BOOKORDER = "drop table if exists bookorder;";

    static final String CREATE_TABLE_BOOKORDER =
            "create table bookorder (" +
                    "  ordernumber VARCHAR(13) NOT NULL," +
                    "  customername VARCHAR(100)," +
                    "  orderdate DATE NOT NULL," +
                    "  discount NUMERIC(8,2) NOT NULL," +
                    "  totalamount INT NOT NULL," +
                    "  PRIMARY KEY (ordernumber));";

    static final String INSERT_BOOKORDER_DATA = "insert into bookOrder (orderNumber, customerName, orderDate, discount, totalAmount) values (?, ?, ?, ?, ?);";

    createTables();
    loadTables();

    static void createTables() throws SQLException {
        Statement stmt = conn.createStatement();
        stmt.execute(DROP_TABLE_BOOKORDER);
        stmt.execute(CREATE_TABLE_BOOKORDER);

    }

    static void loadTables() throws SQLException, FileNotFoundException, ParseException {
    Scanner lineScanner = new Scanner(new File(orderData));
        String headerLine = lineScanner.nextLine();

        float totalOrderAmount = 0.0f;
        String previousKnownOrderNum = null;

        while (lineScanner.hasNextLine()) {
                String[] retrievedOrderLine = lineScanner.nextLine().split("\t");


                // if order number exists
                if (!Objects.equals(retrievedOrderLine[0], "")) {
                    previousKnownOrderNum = retrievedOrderLine[0];

                    // order number
                    bookOrderStmt.setString(1, retrievedOrderLine[0]);

                    //customer name
                    bookOrderStmt.setString(2, retrievedOrderLine[1]);


                    //order date
                    //handle date format conversion
                    String orderDate = retrievedOrderLine[2];
                    System.out.println("now processing book order date as " + retrievedOrderLine[2]);
                    SimpleDateFormat formattedDate = new SimpleDateFormat("yyyy-MM-dd");
                    java.util.Date date = formattedDate.parse(orderDate);
                    java.sql.Date sqlFormattedDate = new java.sql.Date(date.getTime());
                    bookOrderStmt.setDate(3, sqlFormattedDate);

                    // discount
                    bookOrderStmt.setFloat(4, Float.parseFloat(retrievedOrderLine[3]));


            }

                    // if line contains a book isbn
                    if(!Objects.equals(retrievedOrderLine[4], "")) {

                        // if next line contains an orderNumber (the length of the line = 10), then insert accumulated orderTotal into database
                        if (lineScanner.nextLine().length() == 10) {

                            float thisLinesAmount = Float.parseFloat(retrievedOrderLine[5]) * Float.parseFloat(retrievedOrderLine[6]);

                            totalOrderAmount = totalOrderAmount + thisLinesAmount;
                            bookOrderStmt.setFloat(5, totalOrderAmount);

                            // reset total amount
                            totalOrderAmount = 0.0f;

                            // else continue to accumulate
                        } else {

                            // insert a temp value for totalAmount

                            totalOrderAmount = totalOrderAmount + Float.parseFloat(retrievedOrderLine[5]) * Float.parseFloat(retrievedOrderLine[6]);
                            bookOrderStmt.executeUpdate();
                            bookOrderStmt.close();
                        }
                    }

        }
    }
}

测试文件:

OrderNum    CustName    OrderDate   Discount    ISBN    NumCopies   BookPrice   ShipmentID  ShipmentDate    ShipCopies
N201700001  John Doe    2017-4-24   1   1234567891  1   15.99   S0000003    2017-4-25   1
N201700002  Jane Doe    2017-3-1    41.97   1234567890  10  11.99   S0000001    2017-3-2    5
                            S0000002    2017-3-15   5
                1234567891  20  14.99   S0000001    2017-3-2    15
                            S0000002    2017-3-15   5
N201700003  John Jones  2017-5-1    0   1234567891  1   15.99

database table

1 个答案:

答案 0 :(得分:0)

如果你更加面向对象,我认为它会更加清晰。

想想这个助手类(为了简短回答,省略了getters / setter):

 public class BookOrder {
    public String ordernumber;
    public String customerName;
    public Date orderDate;
    public double discount;
    public float totalamount;
    public BookOrder(String on, String cn, Date od, double disc) {
        ordernumber = on;
        customerName = cn;
        orderDate = od;
        discount = disc;
        totalamount = 0;
    }
    public void addAmount(float amount) {
        totalamount += amount * discount;
    }
 }

这样你可以更容易地编写循环:

static void loadTables() {
    Scanner lineScanner = new Scanner(new File(orderData));
    // skip headers
    String headerLine = lineScanner.nextLine();

    BookOrder currentOrder = null;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    while (lineScanner.hasNextLine()) {
            String[] retrievedOrderLine = lineScanner.nextLine().split("\t");

            // if order number exists
            if (!Objects.equals(retrievedOrderLine[0], "")) {
                //Ordernumber changed, but not null
                if(currentOrder != null || 
                        !currentOrder.ordernumber.equals(retrievedOrderLine[0])) {
                    //Insert into DB
                    insertBookOrder(currentOrder);
                }
                //Ordernumber changed or null (first order)
                if(currentOrder == null || 
                        !currentOrder.ordernumber.equals(retrievedOrderLine[0])) {  
                    //Start the next order as ordernumber changed
                    currentOrder =new BookOrder(
                            retrievedOrderLine[0], //ordernumber
                            retrievedOrderLine[1], //customer
                            dateFormat.parse(retrievedOrderLine[2]), //date
                            Float.parseFloat(retrievedOrderLine[3]) //discount
                            );
                }
            }
            //Now add to total (discount is taken care of in method)
            currentOrder.addAmount(Float.parseFloat(retrievedOrderLine[5]));                            
        }
        //Afterwards we need to insert last item if it exists
        if(currentOrder != null) {
            //Insert into DB
            insertBookOrder(currentOrder);
        }
    }