本文介绍了如何使用 ALTER TABLE 语句更改 MySQL 中的默认字符集。
简而言之,有两种方法可以改变表格以使用新的字符集。
更多: zhilu jiaocheng
2. ALTER TABLE tablename CONVERT TO CHARACTER SET utf8;
这会将所有列更改为新字符集并更改表。
所以你最终会得到所需的定义:
mysql> show create table mybig5; +--------+--------------------------------+ | Table | Create Table | +--------+--------------------------------+ | mybig5 | CREATE TABLE `mybig5` ( `id` int(11) NOT NULL AUTO_INCREMENT, `subject` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | +--------+--------------------------------+ 1 row in set (0.00 sec)
因此,如果我们在表上看到不正确的字符串错误,请检查列是否使用与默认值不同的字符集。
查看使用 CONVERT 子句来避免该问题,但也要注意某些表实际上可能需要不同列的不同字符集。
1. ALTER TABLE tablename DEFAULT CHARACTER SET utf8;
这将更改表以使用新字符集作为默认值,但作为安全机制,它只会更改默认字符集的表定义。
也就是说,现有的字符字段将具有每列的旧字符集。
例如:
mysql> create table mybig5 (id int not null auto_increment primary key, -> subject varchar(100) ) engine=innodb default charset big5; Query OK, 0 rows affected (0.81 sec)
mysql> show create table mybig5; +--------+--------------------------------+ | Table | Create Table | +--------+--------------------------------+ | mybig5 | CREATE TABLE `mybig5` ( `id` int(11) NOT NULL AUTO_INCREMENT, `subject` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=big5 | +--------+--------------------------------+ 1 row in set (0.00 sec)
mysql> alter table mybig5 default charset utf8; Query OK, 0 rows affected (0.17 sec) Records: 0 Duplicates: 0 Warnings: 0
插入在 big5 字符集中工作的多字节字符串,例如:
mysql> INSERT INTO mybig5 VALUES (NULL, UNHEX('E7BB8FE79086')); 01:08:19 [INSERT - 0 row(s), 0.000 secs] [Error Code: 1366, SQL State: HY000] Incorrect string value: '\xE7\xBB\x8F\xE7\x90\x86' for column 'SUBJECT' at row 1 ... 1 statement(s) executed, 0 row(s) affected, exec/fetch time: 0.000/0.000 sec [0 successful, 0 warnings, 1 errors]
mysql> show create table mybig5; +--------+------------------------------------------------+ | Table | Create Table | +--------+------------------------------------------------+ | mybig5 | CREATE TABLE `mybig5` ( `id` int(11) NOT NULL AUTO_INCREMENT, `subject` varchar(100) CHARACTER SET big5 DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | +--------+------------------------------------------------+ 1 row in set (0.00 sec)
请注意,“主题”列具有原始字符集定义,并且在插入数据时,如果字符集不匹配,可能会导致上述错误。
日期:2020-09-17 00:11:07 来源:oir作者:oir