简体   繁体   English

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

[英]Inserting or updating a database based on the the next line of a file

I have as a text file: 我有一个文本文件:

在此输入图像描述

which contains information relating to the order of books where a single order can contain multiple copies of one or more books. 其中包含与书籍顺序相关的信息,其中单个订单可以包含一本或多本书籍的多个副本。

I want to compute the total amount a customer spent in a single order, thus numCopies * bookPrice for each ISBN in an order. 我想计算客户在单个订单中花费的总金额,因此订单中每个ISBN的numCopies * bookPrice。 The first order would be (1*15.99) = 15.99. 第一个订单是(1 * 15.99)= 15.99。 The second (10*11.99 + 20*14.99) = 419.70. 第二个(10 * 11.99 + 20 * 14.99)= 419.70。 And the third again (1*15.99). 第三次(1 * 15.99)。

I am going through the text file with scanner, adding elements of the text file into the text file as I go along. 我正在浏览带有扫描仪的文本文件,在我进行时将文本文件的元素添加到文本文件中。 To compute the order total I am trying to accumulate the cost of each book where one is present on a line, until a line is reached where the orderNum changes. 为了计算订单总数,我试图累计每行的成本,其中一行出现在一行上,直到达到orderNum更改的行。 Then insert that total order amount into the database. 然后将总订单金额插入数据库。

Im unsure I can correctly check for when an order total should be released and reset for the next ordernumber and insert this total into the database. 我不确定我是否可以正确检查订单总额何时应该被释放并重置为下一个订单号并将此总数插入数据库。 Or essentially compute the total as I go along and then update the database once I have read all the order data. 或者基本上计算总数,然后在读完所有订单数据后更新数据库。

relevant code: 相关代码:

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();
                        }
                    }

        }
    }
}

test file: 测试文件:

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

数据库表

I think it get's much clearer if you do it a bit more object oriented. 我认为如果你更加面向对象会更清楚。

Think of this helper class (getters/setters omitted for shortness of answer): 想想这个助手类(为简短的答案省略了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;
    }
 }

Which this in place you can write your loop much easier: 这样你可以更容易地编写循环:

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);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM