[英]Java enum in mysql
我想從我的數據庫中放入和取出產品。 該產品的顏色為枚舉
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;
}
}
在這里,我與我的數據庫有關系。 應該有顏色顏色而不是字符串顏色。 我嘗試兩種選擇。 任何建議如何解決它?
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();
}
}
在這種情況下,你可以簡單地做;
Color color = Color.valueOf(resultSet.getString("color"));
應該注意的是,如果 String 不存在枚舉元素,則應該為 IllegalStateException 使用 try-catch。
在一個不相關的筆記上
將您的 Statement 包裹在 try-with-resources 中,否則您將獲得資源泄漏。
try (Statement statement = connection.createStatement()) {
}
考慮使用 PreparedStatement 。
盡可能(應該總是)使用 PreparedStatement 而不是 Statement。 這是一個關於原因的有用鏈接。
不要顯式修改查詢
不要在查詢中插入值。 相反,修改 PreparedStatement 對象。 SQL 注入目前是可能的。 您的查詢將如下所示。
String query = "SELECT * FROM ?";
這將允許您更換 ? 通過執行以下操作使用表名。
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, tableName);
}
方法之一是使用枚舉的名稱值,並使用Color.valueOf(resultSet.getString("color"))
,如其他答案中所述,但還有其他可能性。
更有效的方法是使用枚舉的序數,並將其存儲為 int。 要存儲值,您需要在枚舉上調用 ordinal() 方法。 它返回一個從零開始的索引,因此在您的示例中,WHITE.ordinal() 將返回 0,而 GRAY.ordinal() 將返回 8。
要從數據庫中讀取值,您可以執行以下操作:
Color.values()[resultSet.getInt("color")]
(參見: https : //stackoverflow.com/a/609866/11751648 )
請注意,效率是有代價的:如果你需要修改你的枚舉,你只能在最后添加值,否則如果順序改變,序號值會改變並且你的數據會不連貫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.