MySQL的varchar(10)能存多少個漢字


問題

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個漢字

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM