Mysql設(shè)置字符編碼的方法
Mysql設(shè)置字符編碼可以解決一些常見(jiàn)的問(wèn)題,比如使用不同的字符集出錯(cuò)的問(wèn)題,下面就是Mysql設(shè)置字符編碼解決該問(wèn)題的具體介紹。
錯(cuò)誤是在你的結(jié)果集中有兩種字符集。
比如說(shuō)你在兩個(gè)表聯(lián)合查詢,一個(gè)表的字符集是latin1,另一個(gè)是utf8,
這樣在你的結(jié)果集中有兩種字符集,mysql會(huì)報(bào)錯(cuò)誤。
一個(gè)表中不同的字段使用不同的字符集,也是一個(gè)道理。
用SHOW CREATE TABLE table_name;可以看出具體的字符集設(shè)置。
查了幫助手冊(cè),說(shuō)是user的字符集沒(méi)有設(shè),默認(rèn)為utf8,將其轉(zhuǎn)為latin1或gb2312等字符集
解決方法:
將不同的字符集,轉(zhuǎn)化成統(tǒng)一的字符集。 下面就是Mysql設(shè)置字符編碼的方法。
- After an upgrade to MySQL 4.1, the statement fails:
- mysql> SELECT SUBSTRING_INDEX(USER(),'@',1);
- ERROR 1267 (HY000): Illegal mix of collations
- (utf8_general_ci,IMPLICIT) and (latin1_swedish_ci,COERCIBLE)
- for operation 'substr_index'
- The reason this occurs is that usernames are stored using UTF8 (see section 11.6 UTF8 for Metadata). As a result, the USER() function and the literal string '@' have different character sets (and thus different collations):
- mysql> SELECT COLLATION(USER()), COLLATION('@');
- +-------------------+-------------------+
- | COLLATION(USER()) | COLLATION('@') |
- +-------------------+-------------------+
- | utf8_general_ci | latin1_swedish_ci |
- +-------------------+-------------------+
- One way to deal with this is to tell MySQL to interpret the literal string as utf8:
- mysql> SELECT SUBSTRING_INDEX(USER(),_utf8'@',1);
- +------------------------------------+
- | SUBSTRING_INDEX(USER(),_utf8'@',1) |
- +------------------------------------+
- | root |
- +------------------------------------+
- Another way is to change the connection character set and collation to utf8. You can do that with SET NAMES 'utf8' or by setting the character_set_connection and collation_connection system variables directly.
表的編碼轉(zhuǎn)換可以用:(MySQL Version > 4.12)
- ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name;
之前的版本可以用:
- ALTER TABLE tbl_name CHARACTER SET charset_name;
【編輯推薦】
MySQL數(shù)據(jù)庫(kù)的23個(gè)特別注意事項(xiàng)