java 准备好的语句中的Java枚举到mysql枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1639269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java enum to mysql enum in prepared statement
提问by Johannes
With the regular statement (just statement) I can put java enums into the queries and it works just fine. With prepared statement I can't do this ?
使用常规语句(just 语句),我可以将 java 枚举放入查询中,并且它工作得很好。有了准备好的声明,我不能这样做吗?
回答by ChssPly76
MySQL treats its enum type as string for queries. So you should be able to use PreparedStatement.setString()method and pass enum name to it:
MySQL 将其枚举类型视为用于查询的字符串。所以你应该能够使用PreparedStatement.setString()方法并将枚举名称传递给它:
preparedStatement.setString(1, MY_ENUM.name());
This assumes, of course, that names for your java and MySQL enums match.
当然,这假设您的 java 和 MySQL 枚举的名称匹配。
Notice:name()was chosen instead of toString()as, per the docs:
注意:根据文档,name()被选择而不是toString()作为:
name()This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release.
name()此方法主要设计用于正确性取决于获取确切名称的特殊情况,该名称不会因版本而异。
回答by Marquez
If you'd prefer to store it as integer (which is more space and performance friendly) you could do this:
如果您更愿意将其存储为整数(这对空间和性能更友好),您可以这样做:
preparedStatement.setInt(1, myEnum.ordinal());
PreparedStatement.setInt(1, myEnum.ordinal());
This provides simplicity, however, you must be sure not to change the order of the enum elements in code as that will break their relationship with what is stored in the db.
这提供了简单性,但是,您必须确保不要更改代码中枚举元素的顺序,因为这会破坏它们与存储在数据库中的内容的关系。

