Home Database Mysql Tutorial Mysql数据库编码问题 (修改数据库,表,字段编码为utf8)

Mysql数据库编码问题 (修改数据库,表,字段编码为utf8)

Jun 07, 2016 pm 06:05 PM
mysql

个人建议,数据库字符集尽量使用 utf8(HTML页面对应的是utf-8),以使你的数据能很顺利的实现迁移

因为utf8字符集是目前最适合于实现多种不同字符集之间的转换的字符集,尽管你在命令行工具上可能无法正确查看数据库中的内容,我依然强烈建议使用utf8作为默认字符集
接下来是完整的一个例子:
1.创建数据库表
mysql>CREATE DATABASE IF NOT EXISTS my_db default charset utf8 COLLATE utf8_general_ci;
#注意后面这句话 "COLLATE utf8_general_ci",大致意思是在排序时根据utf8校验集来排序
#那么在这个数据库下创建的所有数据表的默认字符集都会是utf8了

mysql>create table my_table (name varchar(20) not null default '')type=myisam default charset utf8;
#这句话就是创建一个表了,制定默认字符集为utf8

2.写数据
例子1是通过php直接插入数据:
a.php
代码如下:
mysql_connect('localhost','user','password');
mysql_select_db('my_db');
//请注意,这步很关键,如果没有这步,所有的数据读写都会不正确的
//它的作用是设置本次数据库联接过程中,数据传输的默认字符集
//其他编程语言/接口也类似,例如 .net/c#/odbc
//jdbc则设置连接字符串为类似"jdbc:mysql://localhost/db?user=user&password=123456&useUnicode=true&characterEncoding=UTF-8"
mysql_query("set names utf8;");
//必须将gb2312(本地编码)转换成utf-8,也可以使用iconv()函数
mysql_query(mb_convet_encoding("insert into my_table values('测试');", "utf-8", "gb2312"));
?>

例子是通过页面提交插入数据2:
b.php
代码如下:
//输出本页编码为utf-8
header("content-type:text/html; charset=utf-8");

mysql_connect('localhost','user','password');
mysql_select_db('my_db');

if(isset($_REQUEST['name'))
{
//由于上面已经指定本页字符集为utf-8了,因此无需转换编码
mysql_query(sprintf("insert into my_table values('%s');", $_REQUEST['name']));
}

$q = mysql_query("select * from my_table");
while($r = mysql_fetch_row($q))
{
print_r($r);
}
?>






自此,使用utf8字符集的完整的例子结束了.
如果你想使用gb2312编码,那么建议你使用latin1作为数据表的默认字符集,这样就能直接用中文在命令行工具中插入数据,并且可以直接显示出来.而不要使用gb2312或者gbk等字符集,如果担心查询排序等问题,可以使用binary属性约束,例如:
create table my_table ( name varchar(20) binary not null default '')type=myisam default charset latin1;

附1:旧数据升级办法
以原来的字符集为latin1为例,升级成为utf8的字符集。原来的表: old_table (default charset=latin1),新表:new_table(default charset=utf8)。
第一步:导出旧数据
mysqldump --default-character-set=latin1 -hlocalhost -uroot -B my_db --tables old_table > old.sql
第二步:转换编码(类似unix/linux环境下)
iconv -t utf-8 -f gb2312 -c old.sql > new.sql
或者可以去掉 -f 参数,让iconv自动判断原来的字符集
iconv -t utf-8 -c old.sql > new.sql
在这里,假定原来的数据默认是gb2312编码。
第三步:导入
修改old.sql,在插入/更新语句开始之前,增加一条sql语句: "SET NAMES utf8;",保存。
mysql -hlocalhost -uroot my_db 大功告成!!

附2:支持查看utf8字符集的MySQL客户端有
1.) MySQL-Front,据说这个项目已经被MySQL AB勒令停止了,不知为何,如果国内还有不少破解版可以下载(不代表我推荐使用破解版 :-P)。
2.) Navicat,另一款非常不错的MySQL客户端,汉化版刚出来,还邀请我试用过,总的来说还是不错的,不过也需要付费。
3.) PhpMyAdmin,开源的php项目,非常好。
4.) Linux下的终端工具(Linux terminal),把终端的字符集设置为utf8,连接到MySQL之后,执行 SET NAMES UTF8; 也能读写utf8数据了。

附3:直接使用MySQL提供的 ALTER 语法转换字符集
这对广大非utf8又想转成utf8的用户来说,是个天大的喜讯,我也是在学习MySQL手册是才发现的。具体用法如下:
ALTER TABLE OLD_TABLE CONVERT TO CHARACTER SET charset_name [COLLATE collation_name];
转换之前,记得要先备份旧表,以防万一。下面是一个实际的例子:
ALTER TABLE `t_yejr` CONVERT TO CHARACTER SET UTF8;
这个方法应该是从MySQL 4.1才开始提供的,大家可以检查一下自己的版本是否支持,如果不支持,只好按照上面提到的转换了。enjoy it!!!
Statement of this Website
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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mysql whether to change table lock table mysql whether to change table lock table Apr 08, 2025 pm 05:06 PM

When MySQL modifys table structure, metadata locks are usually used, which may cause the table to be locked. To reduce the impact of locks, the following measures can be taken: 1. Keep tables available with online DDL; 2. Perform complex modifications in batches; 3. Operate during small or off-peak periods; 4. Use PT-OSC tools to achieve finer control.

Unable to log in to mysql as root Unable to log in to mysql as root Apr 08, 2025 pm 04:54 PM

The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Apr 08, 2025 pm 07:12 PM

1. Use the correct index to speed up data retrieval by reducing the amount of data scanned select*frommployeeswherelast_name='smith'; if you look up a column of a table multiple times, create an index for that column. If you or your app needs data from multiple columns according to the criteria, create a composite index 2. Avoid select * only those required columns, if you select all unwanted columns, this will only consume more server memory and cause the server to slow down at high load or frequency times For example, your table contains columns such as created_at and updated_at and timestamps, and then avoid selecting * because they do not require inefficient query se

Can mysql handle multiple connections Can mysql handle multiple connections Apr 08, 2025 pm 03:51 PM

MySQL can handle multiple concurrent connections and use multi-threading/multi-processing to assign independent execution environments to each client request to ensure that they are not disturbed. However, the number of concurrent connections is affected by system resources, MySQL configuration, query performance, storage engine and network environment. Optimization requires consideration of many factors such as code level (writing efficient SQL), configuration level (adjusting max_connections), hardware level (improving server configuration).

Can mysql run on android Can mysql run on android Apr 08, 2025 pm 05:03 PM

MySQL cannot run directly on Android, but it can be implemented indirectly by using the following methods: using the lightweight database SQLite, which is built on the Android system, does not require a separate server, and has a small resource usage, which is very suitable for mobile device applications. Remotely connect to the MySQL server and connect to the MySQL database on the remote server through the network for data reading and writing, but there are disadvantages such as strong network dependencies, security issues and server costs.

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

See all articles