Java enum in mysql

Patient Zero :

I would like to put in and put out products from my database. Color of this products are as enums

public enum Color {
WHITE("#FFFFFF"), BLACK("#000000"), GREEN("#008000"), RED("#FF0000"), BLUE("#0000FF"), YELLOW("#FFFF00"), ORANGE("#FFA500"), PURPLE("#800080"),
GRAY("#808080");

private String color;

Color (String color){
    this.color = color;
}

public String getHex() {
    return color;
}

}

Here i have relation with my databases. There should be Color color not as String color. I try both options. Any suggestion how to fix it?

public List<Product> getAllProducts( ){
    List<Product> products = new LinkedList<Product>();
    Statement statement;
    try {
        statement = connection.createStatement();
        query = "select * from " + tableName;
        ResultSet resultSet = statement.executeQuery(query);
        /* (name, price, weight, color, product count, size, material */
        while(resultSet.next()) {
            Long id = resultSet.getLong("id");
            String name = resultSet.getString("name");
            Float price = resultSet.getFloat("price");
            Float weight = resultSet.getFloat("weight");
            String color = resultSet.getString(("color"));
            Integer productCount = resultSet.getInt("productcount");
            String size = resultSet.getString("size");
            String material = resultSet.getString("material");

            Product product = new Product(id, name, price, weight, color, productCount, size, material);
            products.add(product);
        }

    }
    catch (SQLException e) {
        e.printStackTrace();
    }
}
Jason :

In this kind of situation you can simply do;

Color color = Color.valueOf(resultSet.getString("color"));

It should be noted that you should surround with a try-catch for the IllegalStateException if no enum element exists for the String.

On an unrelated note

Wrap your Statement in a try-with-resources or you're going to get resource leaks.

try (Statement statement = connection.createStatement()) {

}

Consider using a PreparedStatement.

Always use a PreparedStatement instead of a Statement when you can (should be always). This is a helpful link on why.

Dont explicitly modify the query

Don't insert values into the query. Instead, modify the PreparedStatement object. SQL injection is currently possible. Your query would look like this.

String query = "SELECT * FROM ?";

This will allow you to replace ? with the table name by doing the following.

try (PreparedStatement statement = connection.prepareStatement(query)) {
    statement.setString(1, tableName);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27102&siteId=1