新聞中心
python連接mysql數(shù)據(jù)庫時,讀取數(shù)據(jù)庫中的中文出現(xiàn)亂碼,所有中文都顯示為問號了。

站在用戶的角度思考問題,與客戶深入溝通,找到任丘網(wǎng)站設(shè)計與任丘網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗,讓設(shè)計與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:成都網(wǎng)站設(shè)計、成都網(wǎng)站制作、外貿(mào)網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣、域名注冊、網(wǎng)站空間、企業(yè)郵箱。業(yè)務(wù)覆蓋任丘地區(qū)。
數(shù)據(jù)庫代碼:
-- 建表語句
CREATE TABLE books (
name varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- 插入數(shù)據(jù)
insert into books values('萬物生光輝');
insert into books values('我親愛的甜橙樹');
insert into books values('教父');
insert into books values('故事');
insert into books values('樹上的男爵');
insert into books values('羅馬人的故事2');
insert into books values('秘島(全三冊)');python代碼:
#!/usr/bin/env python
import pymysql.cursors
connection = pymysql.connect(user='用戶名', passwd='密碼', db='數(shù)據(jù)庫名')
cursor = connection.cursor()
ex = cursor.execute("select name from books")
books = cursor.fetchmany(ex)
for book in books:
print("%s" % book[0])
connection.close()輸出結(jié)果如下:
下面我們就來看一下解決方法:
Python文件設(shè)置編碼 utf-8 (文件前面加上 #encoding=utf-8)
MySQL數(shù)據(jù)庫charset=utf-8
Python連接MySQL是加上參數(shù) charset=’utf8’
讀取數(shù)據(jù)后寫入文件前執(zhí)行編碼book[0].encode(‘utf-8’)
最后測試的時候發(fā)現(xiàn)只需在連接MySQL的時候加上charset=’utf8’即可,以utf-8編碼格式讀取數(shù)據(jù),其他條件無需添加,也不會出現(xiàn)從mysql中讀取的數(shù)據(jù)出現(xiàn)中文亂碼的情況。
網(wǎng)站名稱:創(chuàng)新互聯(lián)Python教程:python中讀取mysql亂碼怎么辦?
網(wǎng)頁網(wǎng)址:http://fisionsoft.com.cn/article/coipdso.html


咨詢
建站咨詢
