当前位置:网站首页>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 .
边栏推荐
- UART
- Lambda&Stream
- [hero planet July training leetcode problem solving daily] 24th line segment tree
- Kubernetes application design guide
- paddlepaddle论文系列之Alexnet详解(附源码)
- What is the function of transdata operator and whether it can optimize performance
- [leetcode weekly replay] game 83 biweekly 20220723
- Redis 事务学习有感
- What are the functions of rank function
- [help] mindspire training based on ascend910 cannot reproduce the model effect on GPU
猜你喜欢

Quartus: install cyclone 10 LP device library for quartus version 17.1

Vscode installation and configuration

【无标题】

Heap and stack in embedded development

NXP i.mx6q development board software and hardware are all open source, and the schematic diagram of the core board is provided

Wechat applet development learning 5 (custom components)
![[help] mindspire training based on ascend910 cannot reproduce the model effect on GPU](/img/b5/c02ef57526d208b02dfa00189e9ecb.jpg)
[help] mindspire training based on ascend910 cannot reproduce the model effect on GPU

Advanced multithreading (Part 2)

Moonpdflib Preview PDF usage record

Use es to realize fuzzy search and search recommendation of personal blog
随机推荐
LeetCode_6124_第一个出现两次的字母
Redis管道技术/分区
Research and Multisim Simulation of linear circuit characteristics (engineering documents attached)
Discussion on line segment tree
Managing databases in a hybrid cloud: eight key considerations
Find the median of two numbers in the fourth question of C language deduction (three methods)
UXDB在不知道明文密码的情况下重置密码
The new version of Alibaba Seata finally solves the idempotence, suspension and empty rollback problems of TCC mode
"Usaco2006nov" corn fields solution
Leetcode 0123. the best time to buy and sell stocks III: dynamic programming + simulation in constant space
Where is the most formal account opening for futures trading? Capital security?
Internal network mapping port to external network
Quartus: install cyclone 10 LP device library for quartus version 17.1
Kubernetes application design guide
[mindspore ascend] [running error] graph_ In mode, run the network to report an error
Redis memory analysis tool RMA usage
Install and configure php5-7 version under centos7.4
ASP rs.open SQL, Conn, what does 3, 1 stand for in 3,1?
js && ||
Palm package manager of kubernetes learning offline installation of NFS client provider