如何创建一个行映射器类来写入返回到bean类的数据库的内容

时间:2019-04-16 21:21:42

标签: java mysql database if-statement javabeans

我正在尝试创建自己的智能冰箱概念设计版本,该设计本质上是在外部USB磅秤上发送食品杂货的加权值(例如,我将使用6个鸡蛋的纸箱)。它将6个鸡蛋存储在一个名为“ fridge”的MySQL数据库表中,每次删除一个鸡蛋时,它将在数据库表“购物清单”中添加一个鸡蛋。到目前为止,我在这方面取得了长足的发展一旦鸡蛋的重量落在我设置的值数组之间,就可以打印出“重量变化”的鸡蛋(如下面我的主班级所示)。基本上,我停留在项目的下一部分,该部分每次权重发生变化时都将值写入数据库表。我有数据库连接,并且有一个查询,一旦重量与EggsWeight整数相同,就会在其中插入鸡蛋值,但是我希望数据库根据重量变化来一致地更新数量值。

import java.io.Console;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.usb.UsbConfiguration;
import javax.usb.UsbDevice;
import javax.usb.UsbDeviceDescriptor;
import javax.usb.UsbEndpoint;
import javax.usb.UsbException;
import javax.usb.UsbHostManager;
import javax.usb.UsbHub;
import javax.usb.UsbInterface;
import javax.usb.UsbPipe;
import javax.usb.UsbServices;
import javax.usb.event.UsbPipeDataEvent;
import javax.usb.event.UsbPipeErrorEvent;
import javax.usb.event.UsbPipeListener;

public class UsbScale implements UsbPipeListener {

    private final UsbDevice device;
    private UsbInterface iface;
    private UsbPipe pipe;
    private byte[] data = new byte[6];

    private UsbScale(UsbDevice device) {
        this.device = device;
    }

    public static void main(String[] args) throws UsbException {

        UsbScale scale = UsbScale.findScale();
        scale.open();
        try {
            for (boolean i = true; i; i = true) {
                scale.syncSubmit();
            }
        } finally {
            scale.close();
        }
    }

    public static UsbScale findScale() throws UsbException {
        UsbServices services = UsbHostManager.getUsbServices();
        UsbHub rootHub = services.getRootUsbHub();
        // Dymo M5 Scale:
        UsbDevice device = findDevice(rootHub, (short) 0x0922, (short) 0x8003);
        // Dymo M25 Scale:
        if (device == null) {
            device = findDevice(rootHub, (short) 0x0922, (short) 0x8005);
        }
        if (device == null) {
            return null;
        }
        return new UsbScale(device);
    }

    private static UsbDevice findDevice(UsbHub hub, short vendorId, short productId) {
        for (UsbDevice device : (List<UsbDevice>) hub.getAttachedUsbDevices()) {
            UsbDeviceDescriptor desc = device.getUsbDeviceDescriptor();
            if (desc.idVendor() == vendorId && desc.idProduct() == productId) {
                return device;
            }
            if (device.isUsbHub()) {
                device = findDevice((UsbHub) device, vendorId, productId);
                if (device != null) {
                    return device;
                }
            }
        }
        return null;
    }

    private void open() throws UsbException {
        UsbConfiguration configuration = device.getActiveUsbConfiguration();
        iface = configuration.getUsbInterface((byte) 0);
        // this allows us to steal the lock from the kernel
        iface.claim(usbInterface -> true);
        final List<UsbEndpoint> endpoints = iface.getUsbEndpoints();
        pipe = endpoints.get(0).getUsbPipe(); // there is only 1 endpoint
        pipe.addUsbPipeListener(this);
        pipe.open();
    }

    private void syncSubmit() throws UsbException {
        pipe.syncSubmit(data);
    }

    public void close() throws UsbException {
        pipe.close();
        iface.release();
    }

    @Override
    public void dataEventOccurred(UsbPipeDataEvent upde) {

        boolean empty = data[1] == 2;
        boolean overweight = data[1] == 6;
        boolean negative = data[1] == 5;
        boolean grams = data[2] == 2;
        int scalingFactor = data[3];
        int weight = (data[4] & 0xFF) + (data[5] << 8);

        // int phoneWeights[] = new int[5];
        // int minWeight = 142;
        //int previous weight=0;

        boolean EggsOnScale = false;
        int[] EggsWeight = { 440, 460 };
        int[] OneEgg = { 60, 75 };
        int count = 0;
        int oldweight=0;

        //oldweight = weight;
        if (oldweight == weight) {
            // do nothing
        } else {
            System.out.println("Weight Changes");
            /* write DB


            //if (weight < oldweight){
            //then something was taken off
             * 
             * remove equivalent amount of eggs from db.fridge.

            //if(db.frdige == 0 eggs){
                //order eggs
            }

            if(weight > oldweight){
                somebody put eggs in the fridge. 
            }
            *
            *
            *


        }*/
            oldweight=weight;
        }

        if (weight != oldweight) {
            while (count <= 5000) {
                count++;
            }
            while (count < 5)
                weight = count++;
        /*
         for(int i=0, i=Length(phoneWeights); i++) { phoneWeights[i] = minweight+i; }
         */

        /*
         * System.out.println(String.format("Weight = %,.1f%s", scaleWeight(weight,
         * scalingFactor), grams ? "g" : "oz"));
         */

        System.out.println("My Weight: " + weight);
        /*if(newweight != oldweight) {
            oldweight = newweight;
            write to db shopping list;
        }*/

        if(EggsWeight[0] <= weight && weight <= EggsWeight[1]) {
            EggsOnScale = true;
            System.out.println("6 Eggs on scale");
            // write one phone to table in db.
            try {
                // create a mysql database connection
                String myDriver = "com.mysql.jdbc.Driver";
                String myUrl = "jdbc:mysql://localhost:3306/smartfridge?autoReconnect=true&useSSL=false";
                Class.forName(myDriver);
                Connection conn = DriverManager.getConnection(myUrl, "root", "admin");

                // the mysql insert statement
                String query = " insert into fridge (name, UnitOfSale, ContentsQuantity, department, AverageSellingUnitWeight)"
                        + " values (?, ?, ?, ?, ?)";

                // create the mysql insert preparedstatement
                PreparedStatement preparedStmt = conn.prepareStatement(query);
                preparedStmt.setString(1, "Eggs");
                preparedStmt.setInt(2, 1);
                preparedStmt.setInt(3, 6);
                preparedStmt.setString(4, "Milk, Butter & Eggs");
                preparedStmt.setBoolean(5, EggsOnScale);

                // execute the preparedstatement
                preparedStmt.execute();

            } catch (Exception e) {
                //e.printStackTrace();
            }
        } else{
            /*if(EggsWeight[0] - OneEgg[0] <= weight && weight <= EggsWeight[1] - OneEgg[1]) {
                String query =" update fridge set ContentsQuantity = ContentsQuantity -1 where name ='Eggs' and ContentsQuantity > 0 ";
                //System.out.println(ContentsQuantity + "Eggs On Scale");*/
                oldweight = weight;
            }
        }
    }
        //} else{
            //EggsOnScale = false;
        //}

        /*
         * boolean empty = data[1] == 2; boolean overweight = data[1] == 6; boolean
         * negative = data[1] == 5; boolean grams = data[2] == 2; int scalingFactor =
         * data[3]; double DozenEggs = 144.0; //double OneEgg = 0.2; int
         * AverageSellingUnitWeight = (data[4] & 0xFF) + (data[5] << 8);
         * 
         * if (empty) { System.out.println("EMPTY"); } else if (overweight) {
         * System.out.println("OVERWEIGHT"); } else if (negative) {
         * System.out.println("NEGATIVE"); } else if (AverageSellingUnitWeight ==
         * DozenEggs) { // then we have a dozen eggs in the fridge. // add 6 eggs to
         * Fridge table in the database.
         * 
         * try { // create a mysql database connection String myDriver =
         * "com.mysql.cj.jdbc.Driver"; String myUrl =
         * "jdbc:mysql://localhost:3306/smartfridge?autoReconnect=true&useSSL=false;";
         * Class.forName(myDriver); Connection conn = DriverManager.getConnection(myUrl,
         * "root", "admin");
         * 
         * // the mysql insert statement String query =
         * " insert into fridge (name, UnitOfSale, ContentsQuantity, department, AverageSellingUnitWeight)"
         * + " values (?, ?, ?, ?, ?)";
         * 
         * // create the mysql insert preparedstatement PreparedStatement preparedStmt =
         * conn.prepareStatement(query); preparedStmt.setString(1, "Eggs");
         * preparedStmt.setInt(2, 1); preparedStmt.setInt(3, 6);
         * preparedStmt.setString(4, "Milk, Butter & Eggs"); preparedStmt.setDouble(5,
         * DozenEggs);
         * 
         * // execute the preparedstatement preparedStmt.execute();
         * 
         * conn.close(); } catch (Exception e) { e.printStackTrace(); } }
         * 
         * else if (AverageSellingUnitWeight == 0) { // goto TEsco API and order half
         * dozen eggs. }
         * 
         * else { // Use String.format since printf causes problems on remote exec
         * System.out.println(String.format("Weight = %,.1f%s",
         * scaleWeight(AverageSellingUnitWeight, scalingFactor), grams ? "g" : "oz")); }
         */

    private double scaleWeight(int weight, int scalingFactor) {
        return weight * Math.pow(10, scalingFactor);
    }

    @Override
    public void errorEventOccurred(UsbPipeErrorEvent upee) {
        Logger.getLogger(UsbScale.class.getName()).log(Level.SEVERE, "Scale Error", upee);
    }
}

我将购物清单和冰箱清单归类为2个bean类中的常规项目。我需要帮助的是创建一个类,该类将在MYSQL Workbench中创建与数据库的连接,而一个'rowmapper'类将其内容写入数据库返回到bean。任何反馈将不胜感激。

0 个答案:

没有答案