简体   繁体   English

mysql 中的 Java 枚举

[英]Java enum in mysql

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

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.应该注意的是,如果 String 不存在枚举元素,则应该为 IllegalStateException 使用 try-catch。

On an unrelated note在一个不相关的笔记上

Wrap your Statement in a try-with-resources or you're going to get resource leaks.将您的 Statement 包裹在 try-with-resources 中,否则您将获得资源泄漏。

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

}

Consider using a PreparedStatement .考虑使用 PreparedStatement

Always use a PreparedStatement instead of a Statement when you can (should be always).尽可能(应该总是)使用 PreparedStatement 而不是 Statement。 This is a helpful link on why. 是一个关于原因的有用链接。

Dont explicitly modify the query不要显式修改查询

Don't insert values into the query.不要在查询中插入值。 Instead, modify the PreparedStatement object.相反,修改 PreparedStatement 对象。 SQL injection is currently possible. SQL 注入目前是可能的。 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);
}

One of the aproaches is using the name value of the Enum, and using Color.valueOf(resultSet.getString("color")) , as explained in other answer, but there are other possibilities.方法之一是使用枚举的名称值,并使用Color.valueOf(resultSet.getString("color")) ,如其他答案中所述,但还有其他可能性。

A more efficient way would be to use the ordinal of the enum, and store it as an int.更有效的方法是使用枚举的序数,并将其存储为 int。 To store the value you need to call the ordinal() method on the enum.要存储值,您需要在枚举上调用 ordinal() 方法。 It returns a zero-based index, so in your example, WHITE.ordinal() would return 0, and GRAY.ordinal() would return 8.它返回一个从零开始的索引,因此在您的示例中,WHITE.ordinal() 将返回 0,而 GRAY.ordinal() 将返回 8。

To read the value from the database you could do:要从数据库中读取值,您可以执行以下操作:

Color.values()[resultSet.getInt("color")]

(see: https://stackoverflow.com/a/609866/11751648 ) (参见: https : //stackoverflow.com/a/609866/11751648

Note that efficiency comes at a price: if you need to modify your enum, you only can add values at the end, otherwise if the order is altered, the ordinal values would change and your data would be incoherent.请注意,效率是有代价的:如果你需要修改你的枚举,你只能在最后添加值,否则如果顺序改变,序号值会改变并且你的数据会不连贯。

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

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