当前位置:网站首页>Example analysis of enum data type in MySQL
Example analysis of enum data type in MySQL
2022-07-25 00:40:00 【Yisu cloud】
Mysql Medium Enum Data type instance analysis
This article mainly introduces Mysql Medium Enum Relevant knowledge of data type instance analysis , The content is detailed and easy to understand , The operation is simple and fast , It has certain reference value , I believe that after reading this article Mysql Medium Enum Data type and instance analysis articles will gain something , Let's have a look .

Mysql Medium enum Type is what we often call enumeration type , Its value range needs to be enumerated when creating a table ( List them one by one ) Explicitly specify . Yes 1 to 255 Enumeration of members requires 1 Byte store ; about 255 to 65535 Members , need 2 Byte store . At most... Is allowed 65535 Members .
enum The bottom layer stores decimal integers , Strictly in order 1,2,3,4,5… array , Do not use it enum To save numbers .
Sometimes you can use enumerations instead of common string types , Enumeration column can store some non duplicate strings into a predefined collection ,MySQL Very compact when storing enumerations , It will be compressed to... According to the number of list values 1 Or 2 In bytes .MySQL Internally, the position of each value in the list is saved as an integer , And in .frm Save in file “ Numbers - character string ” Of a mapping relationship “ Lookup table ”.
Feature verification
new table
CREATE TABLE `mytest` ( `id` int(11) NOT NULL AUTO_INCREMENT, `sex` enum(' male ',' Woman ') DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4;insert data
insert into mytest(sex) values(' male '); // sex = male insert into mytest(sex) values(' Woman '); // sex = Woman insert into mytest(sex) values(1); // sex = male insert into mytest(sex) values('1'); // sex = male insert into mytest(sex) values(' Unknown '); // Insert error ,1265 - Data truncated for column 'sex' insert into mytest(sex) values('0'); // sex = ''insert into mytest(sex) values(0); // Insert error ,1265 - Data truncated for column 'sex'It can be seen from the above that enum Values in mysql The data structure in is similar to an array , And the subscript is from 1 Start calculated , Sum up :
1、 The correct enumeration value can be inserted into the database , Such as : The first 1、2 statement ;
2、 You can insert it into the database through the correct subscript , Such as : The first 3、4 statement ;
3、 Insert '0' Save as an empty string , Such as : The first 6 statement ;
4、 Insert Numbers 0 perhaps ' Unknown ' When things happen, there will be execution errors , Such as : The first 5、7 statement .
Query data
When inquiring , adopt “ Name +0” You can get the position relationship of the modified value in the enumeration , as follows SQL Statement execution result
SELECT id,sex,sex+0 from `mytest` ;
The query results are as follows :

Modify enumeration
Reduce enumeration types
Use ALTER TABLE mytest MODIFY COLUMN sex enum(' male '); Statement can reduce enumeration types , In special cases, if the enumeration value has been used in the record line, it will appear [1265] Data truncated for column error .
Modify the enumeration name
It is the same as reducing enumeration types , You must ensure that the enumeration value is not used by the record line
First insert enumeration
Use ALTER TABLE mytest MODIFY COLUMN sex enum(' Unknown ',' male ',' Woman '); Statement inserts an enumeration at the beginning . stay ** Inserting enumeration in the first part will cause the location relationship of enumeration to change .** Inserting enumeration in the header will cause the relationship between enumeration and location to move backward .
Here's the picture , Insert previous results :

Here's the picture , The result after insertion :

Add enumeration in the middle
Use ALTER TABLE mytest MODIFY COLUMN sex enum(' male ',' Unknown ',' Woman '); Statement inserts an enumeration in the middle . stay ** Inserting enumeration in the middle will cause the location relationship of enumeration to change .** Inserting an enumeration in the middle will cause the relationship between the enumeration and the position after the insertion position to move backward .
Here's the picture , Insert previous results :

Here's the picture , The result after insertion :

Tail insert enumeration ( recommend )
Use ALTER TABLE mytest MODIFY COLUMN sex enum(' male ',' Woman ',' Unknown '); Statement inserts an enumeration at the end . stay ** Inserting an enumeration in the tail will not cause any change in the enumeration value and location relationship .** Since there is no change, the above figure is not shown here .
Enum types use traps
1、 Super not recommended in mysql Set a field type to enum, But the stored value is a number , such as ‘0’,‘1’,‘2’;
explain 1: There will be confusion , because enum You can take values through angle marks , But its angle sign is from 1 Start , For those who are not familiar with this field, there will be an error
explain 2: enum Fields of type are for 0 And ‘0’ There's a big difference , If you use 0 When the angle mark does the operation , Because it doesn't have this angle sign , What you want will report an error ; If you use ‘0’ This value is used to get the enumeration value , And insert it , You will find that it will succeed , But the result of the insertion is a “ empty ”( No null)
All in all , Don't take it. mysql Of enum Type take and save some numbers ; If you have to use this field to save numbers , Please define this field as int, And then in java The code uses the enumeration class to limit the value range of this field !( There's code behind it )
2、 There may be Caused by: java.sql.SQLException: Data truncated for column 'Color' at row 1 ; error
reason :
Jpa By default, integer sequential values are used to persist enumeration types ;
Mysql Enumeration types in Color The order in which values are defined is
RED、GREEN、BLUE, therefore , When these three values are persisted to the database table , The values are 0、1、2;This means that the data stored in the database here is 0、1、2 Numbers like this , instead of
RED、GREEN、BLUEcharacter string , however Mysql What is defined in the database isRED、GREEN、BLUE, There is no other value, so an error is reported
solve : stay entity Use in @Enumerated(EnumType.STRING) Label your enum type properties , If marked , The default is integer.
Enumerate usage examples
stay JPA Use in @Enumerated(EnumType.STRING), This is the recommended method .
Create table statement
CREATE TABLE test4 ( id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, brand VARCHAR(255) NOT NULL, color ENUM('RED','GREEN','BLUE') ) ENGINE = InnoDB;Java In the code , Enumeration class
public enum Color { RED, GREEN, BLUE }Java In the code ,Javabean
@Entity @Table(name="test4") public class ClothesRight { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Enumerated(EnumType.STRING) private Color color; private String brand; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public ClothesRight(Long id, Color color, String brand) { super(); this.id = id; this.color = color; this.brand = brand; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public ClothesRight() { super(); } }Easy to use
public interface Test4RightRepository extends JpaRepository<ClothesRight, Long>{ }@Autowired private Test4RightRepository t4R;/** * Use @Enumrated() Label fields as enumerated data * result Insert... Correctly RED */ @GetMapping(value="/addclothesright") public void GetTest4Right(){ List<ClothesRight> entities = new ArrayList<>(); ClothesRight clothes = new ClothesRight(); //clothes.setId(1L); clothes.setBrand(" Giordano "); clothes.setColor(Color.RED); entities.add(clothes); t4R.save(entities); }Insert a numerical example ( Not recommended )
mysql Enumerating field types should not be inserted with numbers , But needs are numbers , What do I do ?
solve :mysql The data type is defined as int, Enumeration is limited to java Solve in code
Create table statement
CREATE TABLE test5num ( id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, used int(11) DEFAULT NULL COMMENT '0: Never used 1: Used 2: Out-of-service ' )ENGINE = InnoDB;
Java Code
@[email protected](name="test5num")public class Test5Num { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private Used used; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Used getUsed() { return used; } public void setUsed(Used used) { this.used = used; } public Test5Num() { super(); } public Test5Num(Long id, Used used) { super(); this.id = id; this.used = used; } }
/*** Enumeration class */public enum Used { UNUSED(0," Never used "), USED(1," Used "), FORBIDDEN(2," Out-of-service "); private Integer code; private String discribe; public Integer getCode() { return code; } public String getDiscribe() { return discribe; } private Used(Integer code, String discribe) { this.code = code; this.discribe = discribe; }}/** * dao layer */public interface Test5NumRepository extends JpaRepository<Test5Num, Long>{ }@Autowiredprivate Test5NumRepository t5N; /** * mysql Enumerating field types should not be inserted with numbers , But needs are numbers , What do I do ? * solve :mysql The data type is defined as int, Enumeration is limited to java Solve in code * */@GetMapping("/test5insert")public void insertT5(){ Test5Num t5 = new Test5Num(); t5.setUsed(Used.USED); List<Test5Num> list = new ArrayList<Test5Num>(); list.add(t5); t5N.save(list);}About “Mysql Medium Enum Data type instance analysis ” That's all for this article , Thank you for reading ! I'm sure you're right “Mysql Medium Enum Data type instance analysis ” Knowledge has a certain understanding , If you want to learn more , Welcome to the Yisu cloud industry information channel .
边栏推荐
- Redis管道技术/分区
- ROS manipulator movelt learning notes 3 | kinect360 camera (V1) related configuration
- Vscode installation and configuration
- Automated test series selenium three kinds of waiting for detailed explanation
- What is the function of transdata operator and whether it can optimize performance
- Simple use of mongodb database
- R language plot visualization: plot to visualize the residual analysis diagram of the regression model, the scatter diagram of the predicted value and residual corresponding to the training set and th
- Leetcode 0125. validate palindrome string
- ROS机械臂 Movelt 学习笔记3 | kinect360相机(v1)相关配置
- [untitled]
猜你喜欢

UART

EF core: self referencing organizational structure tree
![[mindspore] [training warning] warning when executing training code](/img/5a/978889301bdd02d6474c6e5723ad97.jpg)
[mindspore] [training warning] warning when executing training code

2022 Henan Mengxin League game 2: Henan University of technology K - Rice

Nodejs package
![[leetcode weekly replay] 303rd weekly 20220724](/img/ba/0f16f1f42e4a2593ec0124f23b30d7.png)
[leetcode weekly replay] 303rd weekly 20220724

Install software on kubernetes cluster using helm 3 package manager

What is the root password of MySQL initial installation
![[mindspore] [xception model] script statement is suspected to be wrong](/img/86/3174f9edadf4b815a76678551cbfa5.jpg)
[mindspore] [xception model] script statement is suspected to be wrong

自动化测试系列-Selenium三种等待详解
随机推荐
Codeworks round 649 (Div. 2) ABC problem solution
[leetcode weekly replay] game 83 biweekly 20220723
【无标题】
UART
Summary of MATLAB basic grammar
R language uses ISNA function to check whether the list and dataframe contain missing values, marks abnormal values in data columns in dataframe as missing values Na, and uses na.omit function to dele
Detailed usage of iperf
The font changes with the change of the form
What can testers do when there is an online bug?
Educational events
Redis memory analysis tool RMA usage
Server intranet and Extranet
Managing databases in a hybrid cloud: eight key considerations
第四章 驱动子系统开发
Why does [mindspore ascend] [custom operator] repeatedly assign values to one tensor affect another tensor?
LeetCode_6124_第一个出现两次的字母
Several states of the process
Educational codeforces round 89 (rated for Div. 2) ABC problem solution
2022 Henan Mengxin League game 2: Henan University of technology I - 22
The new version of Alibaba Seata finally solves the idempotence, suspension and empty rollback problems of TCC mode