在使用MySQL數(shù)據(jù)庫(kù)進(jìn)行開發(fā)的過程中,我們常常會(huì)涉及到數(shù)據(jù)庫(kù)鏈接編碼設(shè)置問題。這是因?yàn)镸ySQL數(shù)據(jù)庫(kù)默認(rèn)使用的編碼為L(zhǎng)atin1編碼,而我們應(yīng)用程序中使用的編碼一般為UTF8編碼,因此需要進(jìn)行編碼設(shè)置。下面我們就來詳細(xì)介紹一下如何進(jìn)行MySQL數(shù)據(jù)庫(kù)鏈接編碼設(shè)置。
一、數(shù)據(jù)庫(kù)字符集設(shè)置
mysql>show variables like '%character%'; +--------------------------+---------------------------------------------------------+ | Variable_name | Value | +--------------------------+---------------------------------------------------------+ | character_set_client | utf8mb4 | | character_set_connection | utf8mb4 | | character_set_database | utf8mb4 | | character_set_filesystem | binary | | character_set_results | utf8mb4 | | character_set_server | utf8mb4 | | character_set_system | utf8 | | character_sets_dir | /usr/local/mysql-5.7.30-linux-glibc2.12-x86_64/share/charsets/ | +--------------------------+---------------------------------------------------------+ 8 rows in set (0.00 sec)
二、MySQL字符集設(shè)置
mysql>show variables like '%collation%'; +----------------------+--------------------+ | Variable_name | Value | +----------------------+--------------------+ | collation_connection | utf8mb4_general_ci | | collation_database | utf8mb4_general_ci | | collation_server | utf8mb4_general_ci | +----------------------+--------------------+ 3 rows in set (0.00 sec)
三、PHP連接MySQL字符集設(shè)置
四、Python連接MySQL字符集設(shè)置
import MySQLdb host = 'localhost' user = 'root' password = '' database = 'test' port = 3306 #連接數(shù)據(jù)庫(kù) conn = MySQLdb.Connect(host=host, user=user, passwd=password, db=database, port=port, charset='utf8mb4')通過以上設(shè)置,我們就可以順利進(jìn)行MySQL數(shù)據(jù)庫(kù)的鏈接編碼設(shè)置,避免出現(xiàn)數(shù)據(jù)亂碼等問題,提高開發(fā)效率。