【问题标题】:Changing character set in MySQL更改 MySQL 中的字符集
【发布时间】:2013-04-30 02:19:53
【问题描述】:

当我启动我的网站时,我将所有表格列设置为“utf8_general_ci”,认为这会使所有内容都以 UTF8 存储。

根据 PHP 中的 mysql_client_encoding() 函数,我一直使用 latin1 进行连接。

我知道这不是一个新问题。我的问题是如何正确更新我的数据库,使其 utf8 并且不影响我的表中存在的数据?

StackOverflow 有很多答案,但我发现很多都含糊不清。几个更有帮助的是:

查询所有数据并更新为UTF8 https://stackoverflow.com/a/2335254/158126

使用构建的脚本转换表格https://stackoverflow.com/a/13400547/158126

根据您的经验,您采取了哪些措施来解决此问题并将所有用户数据保留在 MySQL 表中?

【问题讨论】:

    标签: mysql utf-8 latin1


    【解决方案1】:

    对于您的情况,我建议尝试关注每个坏列(通过 utf8 连接连接):

    // create a new column to store the latin1
    alter table <table> add <column-latin1> <length> character set latin1;
    
    // copy the utf8 data into the latin1 column without charset conversion
    update <table> set <column-latin1> = binary <column-utf8>;
    
    // verify the latin1 data looks OK
    select <column-latin1> from <table>;
    
    // copy the latin1 column into the utf8 column WITH charset conversion
    update <table> set <column-utf8> = <column-latin1>;
    
    // verify the new, properly encoded UTF8 data looks OK
    select <column-latin1> from <table>;
    
    // remove the temporary columns
    alter <table> drop <column-latin1>;
    

    并将您的客户端设置为使用 UTF8 连接。

    【讨论】:

    • 谢谢@svidgen。如果我将客户端设置为使用 UTF8 连接,是否需要将 MySQL 数据库的设置更新为 UTF8?例如:默认字符集=utf8?或者我的代码中的 mysql_set_charset() 会是我未来工作所需要的吗?在你的第二个例子中,它会是 MySQL 查询中的 BINARY(column-utf8) 吗?我以前从未使用过 BINARY 函数。
    • Server characterset 和服务器、数据库和表上的 default* 设置确定在创建时没有明确分配字符集的字段的字符集。 BINARY 关键字指示 MySQL 处理数据,就好像它不是文本一样。因此,上面的第一个update 将逐字节复制column-utf8 的内容到column-latin1。第二个update 以另一种方式通过 字符集转换复制,因为MySQL 将其解释为文本。
    猜你喜欢
    • 1970-01-01
    • 2020-04-19
    • 2018-11-13
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 2015-09-29
    • 1970-01-01
    相关资源
    最近更新 更多