search
HomeDatabaseMysql TutorialMySql中UTF8 和 GBK 编码中文字符长度问题

MySql中UTF8 和 GBK 编码中文字符长度问题

Jun 07, 2016 pm 04:38 PM
gbkmysqlutf8Chinesecharactercodinglengthquestion

为什么要了解MySql中UTF8 和 GBK 编码中文字符长度呢?举个例子,在oracle中用utf8 字段中文长度为1的话,需要char(3),mysql中则是char(1),如果你按照oracle的做法去创建mysql字段,是不是在mysql表中创建的长度大小与自己锁想的不一样呢,所以这个小知

为什么要了解MySql中UTF8 和 GBK 编码中文字符长度呢?举个例子,在oracle中用utf8 字段中文长度为1的话,需要char(3),mysql中则是char(1),如果你按照oracle的做法去创建mysql字段,是不是在mysql表中创建的长度大小与自己锁想的不一样呢,所以这个小知识点还是有必要了解的。
我在经过实验后得到以下结论(适用MySQL 5.0以上版本):

1.一个汉字占多少长度与编码有关:
???????? UTF-8:一个汉字=3个字节
??????????? GBK:一个汉字=2个字节
?2.在MySQL中 varchar(n)和char(n)表示n个字符,无论汉字和英文,Mysql都能存入n个字符,仅是实际字节长度有所区别

???? 即?MySQL 并不会对超过长度的字符报错,而是直接截断了. 并且 char(2) 和 varchar(2) 都能存储 2个汉字,或者是两个英文字符.?
?3. MySQL 的 char(n) 和varchar(n)?可以直接存储 n 个汉字. 而不是 n/3或者 n/2 个,mysql 屏蔽了具体的存储细节,而直接以实际字符的个数来决定char存储的个数


?提示:MySQL检查长度,可用SQL语言:
??????? select LENGTH(fieldname) from tablename?和 select CHAR_LENGTH(fieldname) from tablename?来查看

??????? 说明:LENGTH 输出的结果是 字符实际长度的,而 CHAR_LENGTH输出的则是屏蔽了字符存储细节,是实际的字符个数!

??????? 注:在涉及中文环境下的php+mysql组合,最好是用 mb_strlen来检测字符长度, 而在mysql 中,使用 CHAR_LENGTH来检测字符长度,这样能做到中英文统一处理.?
??????????????? php中strlen和mb_strlen,count的区别:

???????????????? strlen 计算字符串长度,一个中文当2字符;mb_strlen根据它的字符编码模式,统计字符;count计算数组中的元素数目或对象中的属性个数

?

下面我们来验证下我们的结论是否正确:

测试一:

首先,我们先来测试一下 php 把一个汉字认作几个字节:

UTF8测试

 

<?php header("Content-type:text/html;charset=utf-8");
$string1="字";//定义中文字符变量
$string2="x";//定义英文字符变量
//直接输出看看他们的长度
echo strlen($string1);
echo "";
echo strlen($string2);
echo "";
//用 php 多字节扩展函数 mb_strlen试试看
echo mb_strlen($string1,&#39;utf8&#39;);
echo "";
echo mb_strlen($string2,&#39;utf8&#39;);
echo "";
?>

 

注:测试的时候请将test.php文件的编码也改为utf8 ,否则会出现strlen长度为2的情况,得不到正确的结果

输出:

GBK测试:

<?php header("Content-type:text/html;charset=gbk");
$string1="字";//定义中文字符变量
$string2="x";//定义英文字符变量
//直接输出看看他们的长度
echo strlen($string1);
echo "";
echo strlen($string2);
echo "";
//用 php 多字节扩展函数 mb_strlen试试看
echo mb_strlen($string1,&#39;gbk&#39;);
echo "";
echo mb_strlen($string2,&#39;gbk&#39;);
echo "";
?>

输出:

?

结论1.一个汉字占多少长度与编码有关:
???????? UTF-8:一个汉字=3个字节
??????????? GBK:一个汉字=2个字节


测试二:

首先我们来测试UTF8

创建UTF8编码的数据库

CREATE DATABASE `testutf8` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

?

创建utf8编码的表test

CREATE TABLE test(
txt_charchar( 2 ) NULL ,
txt_varchar varchar( 2 ) NULL 
) ENGINE = MYISAM 


确认表字段是否为utf8

插入两条记录:

INSERT INTO test(txt_char,txt_varchar) VALUES ('abcdef','uvwxyz') , ('我是测试的','测试的是我'); 

插入结果:

?

创建test2表

CREATE TABLE `testutf8`.`test2` (
`txt_char` CHAR( 2 ) CHARACTER SET gbk COLLATE gbk_chinese_ci NOT NULL ,
`txt_varchar` VARCHAR( 2 ) CHARACTER SET gbk COLLATE gbk_chinese_ci NOT NULL 
) ENGINE = MYISAM 

确认表字段是否为gbk

插入两条记录:

INSERT INTO test(txt_char,txt_varchar) VALUES ('abcdef','uvwxyz') , ('我是测试的','测试的是我'); 

插入结果:

结论二:

证明 mysql 并不会对超过长度的字符报错,而是直接截断了.
并且 char(2) 和 varchar(2) 都能存储 2个汉字,或者是两个英文字符.
证明 mysql 的 char(n) 可以直接存储 n 个汉字. 而不是 n/3 个
mysql 屏蔽了具体的存储细节,而直接以实际字符的个数来决定 char存储的个数

.

 



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.