search
HomeDatabaseMysql Tutorialset names 命令在mysql中除了应付乱码还能做什么?_MySQL

做一个实验,控制台进入mysql数据库,依次执行如下代码:

#创建数据库

create database it_1 charset utf8;

#进入数据库

use it_1;

#创建表

create table student(id int unsigned primary key auto_increment,stu_no char(9) not null,stu_name varchar(5) not null,stu_sex enum('男','女','保密') default '男',stu_age tinyint not null,c_id int unsigned);

#以上操作全部成功,下面的操作开始报错

#往表中插入记录

insert into student values(null,'itcast101','张三',default,18,1),(null,'itcast102','小李子',2,17,3);

结果会出现如下错误提示:

Data too long for colomn 'stu_name' at row 2#在第二行中'stu_name'字段输入的数据长度太长了

试着只运行第一行,即:

insert into student values(null,'itcast101','张三',default,18,1);#Query OK, 1 row affected

所以这里的异常现象可以描述为'stu_name'字段的预设长度为5个字符(即理论上预留了5个汉字的长度),但实际插入数据时最多只能插入2个汉字。


我马上想到了编码问题,便逐一查看各种可能影响的编码:

1.控制台的编码:gbk

2.student数据库的编码:utf-8

3.'stu_name'字段的编码可以通过如下规则确定:

    a.如果字段设置了字符集就用字段设置

    b.如果没有就找表字符集设置

    c.如果还没有就找数据库字符集设置

    d.如果还没有就找mysql系统配置的默认字符集

显然这里第c.条生效,'stu_name'字段使用utf-8字符集


我知道数据库操作中字符编码不一致会导致乱码问题,而这里控制台中的默认编码与'stu_name'字段的编码明显不一致,数据库中会不会出现乱码呢,于是我用以下三条语句逐一进行测试:

select * from student;

desc student;

show create table student;

结果是都没有出现乱码。由于目前相关知识有限,于是我就凌乱了。。。

通过请教朋友有后,得到了这样的解决方法:

在建表前加入一条命令 

set names gbk;

这条命令的作用是告知mysql服务器,从客户端传来的(这里是控制台输入的)信息采用字符集gbk,而且从mysql服务器发送回客户端的结果也要用字符集gbk。

如果不使用这个命令,那么控制台输入的信息实际采用字符集gbk,但mysql服务器误认为是utf-8字符集,不进行转换就接收了。由于utf-8字符集里中文使用三个字节来编码英文只用1个字节,gbk字符集里中、英文都是使用2个字节来编码,于是控制台传递过去的3个gbk码中文字符(6字节)没有被mysql服务器识别为中文,而是直接识别成了6个英文字符,所以超出了最长5个字符的字段长度限制,导致此处的错误出现。

set names 命令能做的原来不只是应付乱码问题。


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
MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

MySQL's Role: Databases in Web ApplicationsMySQL's Role: Databases in Web ApplicationsApr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

MySQL: Building Your First DatabaseMySQL: Building Your First DatabaseApr 17, 2025 am 12:22 AM

The steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.

MySQL: A Beginner-Friendly Approach to Data StorageMySQL: A Beginner-Friendly Approach to Data StorageApr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

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.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools