問題
MySQL的varchar(10)能存多少個漢字?
如果是數字或英文,可以存10個,如果是漢字呢,能存多少個?
實踐
查看MySQL版本號:
select version();
select @@version;
本機MySQL版本為5.6.16。
創建測試表:
create table test_table (
id bigint(20) not null,
product_code varchar(10) not null,
primary key (id)
) engine=innodb default charset=utf8mb4;
先用數字來測試下,寫入10個數字:
insert into test_table(id,product_code) values(1,'1234567890');
寫入成功,查詢數據:
select id,product_code,length(product_code), char_length(product_code) from test_table;
查詢結果:
id | product_code | length(product_code) | char_length(product_code) |
---|---|---|---|
1 | 1234567890 | 10 | 10 |
其中,length()返回的字節數為10,char_length()返回的字符數也為10。
寫入11個數字試試:
insert into test_table(id,product_code) values(2,'12345678901');
寫入報錯,錯誤提示為:
[22001][1406]Data truncation: Data too long for column 'product_code' at row ...
因為超過10個數字了,因此寫入失敗。
接下里用漢字試試,寫入10個漢字:
insert into test_table(id,product_code) values(3,'天青色等煙雨而我在等');
寫入成功,查詢數據:
select id,product_code,length(product_code), char_length(product_code) from test_table;
查詢結果:
id | product_code | length(product_code) | char_length(product_code) |
---|---|---|---|
1 | 1234567890 | 10 | 10 |
3 | 天青色等煙雨而我在等 | 30 | 10 |
其中,漢字的length()返回的字節數是30,char_length()返回的字符數為10,
可見,1個漢字占3個字節,MySQL把漢字當作字符處理,varchar(10)可存儲的漢字數為10。
寫入11個漢字試試:
insert into test_table(id,product_code) values(4,'天青色等煙雨而我在等你');
寫入報錯,錯誤提示為:
[22001][1406]Data truncation: Data too long for column 'product_code' at row ...
1個漢字占1個字符,11個漢字超過10個字符,因此寫入失敗。
總結
當MySQL版本為5.6時:
- varchar(10)表示存儲的字符數為10,1個漢字占1個字符(3個字節)
- varchar(10)可存儲10個漢字
參考
- mysql varchar(50)到底能存多少個漢字 https://blog.csdn.net/u012491783/article/details/78339269
- 一篇文章看懂mysql中varchar能存多少漢字、數字,以及varchar(100)和varchar(10)的區別 https://www.cnblogs.com/zhuyeshen/p/11642211.html