Как ограничить, если условие только один раз выполнения SQL-запроса в Java - PullRequest
0 голосов
/ 07 марта 2019

Я передаю SQL-запрос через оператор if, как показано ниже. Мне было интересно, как я могу ограничить запрос от выполнения бесконечных раз только один раз? Мне нужен цикл, поскольку он постоянно взвешивает то, что находится на шкале, и когда значение находится в диапазоне моего массива, он выполняет запрос, но он выполняется многократно, пока вес находится в этом диапазоне. Есть ли способ обойти это, когда после выполнения он не будет выполняться снова, даже если вес все еще находится в диапазоне?

 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 phoneOnScale = false;
        int[] phoneWeight = {140,150};

        /*
         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(phoneWeight[0] <= weight && weight <= phoneWeight[1]) {
            phoneOnScale = true;
            System.out.println("Phone is 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";
                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, phoneOnScale);

                // execute the preparedstatement
                preparedStmt.execute();


            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            phoneOnScale = false;
        }

1 Ответ

0 голосов
/ 03 июля 2019

То, что вы можете попытаться сделать, это установить в начале логическое значение false.Затем создайте еще один цикл if перед запросом, который будет выполнять запрос только в том случае, если он равен false.Затем после выполнения запроса измените переменную на true с помощью самого цикла.В псевдокоде

boolean querychecker = False
#this would have to be done outside your other loop. Maybe at the beginning of the class.
if (querychecker == False){
    do(query)
    querychecker = True
}
else {
   #whatever you want to do
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...