当前位置:网站首页>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 .
边栏推荐
- This visual is not connected to the presentationsource.
- Tencent low code platform is officially open source! You can drag and drop and generate mobile phone projects and PC projects! Get private benefits
- Leetcode 0125. validate palindrome string
- MySQL的最左前缀原则
- UXDB在不知道明文密码的情况下重置密码
- [英雄星球七月集训LeetCode解题日报] 第24日 线段树
- Several states of the process
- asp adodb.stream对象的方法属性
- [mindspore ascend] [user defined operator] graph_ In mode, customize how to traverse tensor
- Does opengauss support using Sqlalchemy connections?
猜你喜欢

阿里 Seata 新版本终于解决了 TCC 模式的幂等、悬挂和空回滚问题

paddlepaddle论文系列之Alexnet详解(附源码)

Uncaught typeerror: cannot read properties of null (reading 'append') solution

UART

EF core :自引用的组织结构树

===、==、Object. Is basic package type

Which automation tools can double the operation efficiency of e-commerce?

ROS manipulator movelt learning notes 3 | kinect360 camera (V1) related configuration

Managing databases in a hybrid cloud: eight key considerations

EF core: self referencing organizational structure tree
随机推荐
Internal network mapping port to external network
Log4j configuration file
Codeworks round 649 (Div. 2) ABC problem solution
Chapter III kernel development
Advanced function of postman
2012.4.13 360 written examination summary
[mindspore] [xception model] script statement is suspected to be wrong
Why do I have to clean up data?
2022 Henan Mengxin League game (2): Henan University of technology d-pair
BGP机房和BGP
Educational events
Usage of atomicinteger (counter)
NXP i.mx6q development board software and hardware are all open source, and the schematic diagram of the core board is provided
Lambda&Stream
How to use measurement data to drive the improvement of code review
What is the function of transdata operator and whether it can optimize performance
494. Target sum · depth first search · knapsack problem
Kubernetes application design guide
Heavy forecast! Analysys, together with Microsoft and the Central University of Finance and economics, talks about the digital economy
torch.nn.SyncBatchNorm.convert_ sync_ Mindspore usage corresponding to batchnorm