Как правильно выполнить запрос Java sql с несколькими логическими функциями - PullRequest
0 голосов
/ 11 февраля 2020

Я хочу, чтобы все логические значения были истинными, чтобы можно было использовать последнюю функцию "insertSale ()". Я пытался с частным Int "Provera". Когда логическое значение истинно, «provera» добавляет 1 к своему значению, поэтому для provera должно быть значение 4, если я хочу использовать функцию InsertSale (). Но проблема в том, что когда я запускаю приложение и вставляю значения, которые существуют в базе данных, значение «provera» по-прежнему равно 0. Как мне это сделать?

Сначала я проверяю, существует ли клиент в базе данных.

private boolean customerExists() throws SQLException, ClassNotFoundException {
    Class.forName("com.mysql.jdbc.Driver");
    try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/webshop", "root", "traktor123");) {

        if (customer != null && !(customer.isEmpty())) {
            Statement st = conn.createStatement();
            st.executeQuery("select name from customer where (name='" + customer + "')");
        }
        provera = provera+1;
        return true;

    } catch (SQLException ex) {
        System.out.println("Error in database: \n" + ex.getMessage());
        return false;
    }
}

Затем я проверяю, существует ли продукт.

private boolean productExists() throws SQLException, ClassNotFoundException {
    Class.forName("com.mysql.jdbc.Driver");
    try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/webshop", "root", "traktor123");) {

        if (product != null && !(product.isEmpty())) {
            Statement st = conn.createStatement();
            st.executeQuery("select productName from product where (productName = '" + product + "')");
        }
        provera = provera+1;
        return true;
    } catch (SQLException ex) {
        System.out.println("Error in database: \n" + ex.getMessage());
        System.out.println("Produkt ne postoji");
        return false;
    }
}

Мне нужно найти количество продуктов. Если существует и клиент, и продукт, эту функцию необходимо использовать.

public boolean findQuantity() throws ClassNotFoundException, SQLException {
    Class.forName("com.mysql.jdbc.Driver");
    if (customerExists() == true && productExists() == true) {
        try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/webshop", "root", "traktor123");) {
            Statement st = conn.createStatement();
            st.executeQuery("select quantity from product where (productName='" + product + "')");
            ResultSet rs = st.getResultSet();
            while (rs.next()) {
                if (Integer.parseInt(rs.getString("quantity")) != 0) {
                    finalQuantity = Integer.parseInt(rs.getString("quantity"));
                } 
            }
            provera = provera+1;
            return true;
        } catch (SQLException ex) {
            System.out.println("Error in database: \n" + ex.getMessage());
            return false;
        }
    } 
    return false;

}

Когда я нахожу значение оставшегося количества, я хочу иметь меньше, когда клиент его покупает.

private boolean lessQuantity() throws ClassNotFoundException, SQLException {
    Class.forName("com.mysql.jdbc.Driver");
    if (findQuantity() == true) {
        try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/webshop", "root", "traktor123");) {
            Statement st = conn.createStatement();
            st.execute("update webshop.product set quantity = '" + (finalQuantity - 1) + "' where productName = '" + product + "'");
            provera = provera+1;
            return true;
        } catch (SQLException ex) {
            System.out.println("Error in database: \n" + ex.getMessage());
            return false;
        }
    }
    return false;
}

Этот код необходимо использовать, только если все функции верны.

public void insertSale() throws SQLException, ClassNotFoundException {
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println(provera);
    if(provera == 4){
        try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/webshop", "root", "traktor123");) {
            Statement st = conn.createStatement();
            st.execute("insert into sale (customer, product) values ('" + customer + "','" + product + "')");
            lessQuantity();
        } catch (SQLException ex) {
            System.out.println("Error in database: \n" + ex.getMessage());
        }
    }
}

1 Ответ

0 голосов
/ 12 февраля 2020

Способ работы:

private boolean customerExists() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
        try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/webshop", "root", "traktor123");) {
            Statement st = conn.createStatement();
            if (customer != null && !(customer.isEmpty())) {
                st.executeQuery("select name from customer where (name='" + customer + "')");
            }
            ResultSet rs = st.getResultSet();
            if (rs.next()) {
                return true;
            }

        } catch (SQLException ex) {
            System.out.println("Error in database: \n" + ex.getMessage());
            return false;
        }
        System.out.println("Customer doesn't exist");
        return false;
    }

    private boolean productExists() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
        try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/webshop", "root", "traktor123");) {
            Statement st = conn.createStatement();
            if (product != null && !(product.isEmpty())) {
                st.executeQuery("select productName from product where (productName = '" + product + "')");
            }
            ResultSet rs = st.getResultSet();
            if (rs.next()) {
                return true;
            }
        } catch (SQLException ex) {
            System.out.println("Error in database: \n" + ex.getMessage());
            return false;
        }
        System.out.println("Product doesn't exist");
        return false;
    }

    public boolean findQuantity() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        if (customerExists() == true && productExists() == true) {
            try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/webshop", "root", "traktor123");) {
                Statement st = conn.createStatement();
                st.executeQuery("select quantity from product where (productName='" + product + "')");
                ResultSet rs = st.getResultSet();
                while (rs.next()) {
                    if (Integer.parseInt(rs.getString("quantity")) != 0) {
                        finalQuantity = Integer.parseInt(rs.getString("quantity"));
                        return true;
                    }else{
                        System.out.println("Product quantity is 0");
                    }
                }
            } catch (SQLException ex) {
                System.out.println("Error in database: \n" + ex.getMessage());
                return false;
            }
        }
        return false;

    }

    private boolean lessQuantity() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        if (findQuantity() == true) {
            try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/webshop", "root", "traktor123");) {
                Statement st = conn.createStatement();
                st.execute("update webshop.product set quantity = '" + (finalQuantity - 1) + "' where productName = '" + product + "'");
                return true;
            } catch (SQLException ex) {
                System.out.println("Error in database: \n" + ex.getMessage());
                return false;
            }
        }
        return false;
    }

    public void insertSale() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
        if (lessQuantity() == true) {
            try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/webshop", "root", "traktor123");) {
                Statement st = conn.createStatement();
                st.execute("insert into sale (customer, product) values ('" + customer + "','" + product + "')");
                System.out.println("Successfully bought");
            } catch (SQLException ex) {
                System.out.println("Error in database: \n" + ex.getMessage());
            }
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...