日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:python向數(shù)據(jù)庫(kù)insert亂碼怎么解決?

python向數(shù)據(jù)庫(kù)中insert數(shù)據(jù)出現(xiàn)亂碼解決方法:

保證以下四項(xiàng)的編碼都是utf-8:

1. 代碼

2. 數(shù)據(jù)庫(kù)連接

3. 表的字符集格式

4. 插入的數(shù)據(jù)格式

每步的操作如下:

1. 保證代碼的格式是utf-8,在代碼最前面加上這句話

# -*- coding:utf8 -*-
#首先用于確定編碼,加上這句

2. 保證數(shù)據(jù)庫(kù)連接格式是utf-8,這么寫

conn=MySQLdb.connect(host='localhost',user='root',passwd='****',db='kfxx',port=3306,charset='utf8')
cur=conn.cursor()

3. 保證表的字符集格式是utf-8,在建表的時(shí)候就能設(shè)置

4. 保證插入的數(shù)據(jù)格式是utf-8,分為保證讀取的頁(yè)面格式是utf-8和字符串格式也是utf-8

#解決亂碼問題
html_1 = urllib2.urlopen(cityURL,timeout=120).read()
mychar = chardet.detect(html_1)
bianma = mychar['encoding']
if bianma == 'utf-8' or bianma == 'UTF-8':
      html = html_1
else :
      html = html_1.decode('gb2312','ignore').encode('utf-8')
chapter_soup = BeautifulSoup(html)
city = chapter_soup.find('div',class_ = 'row-fluid').find('h1').get_text()
province = chapter_soup.find('a',class_ = 'province').get_text()
pmNum = chapter_soup.find('div',class_ = 'row-fluid').find('span').get_text()
suggest = chapter_soup.find('div',class_ = 'row-fluid').find('h2').get_text()
rand = chapter_soup.find('div',class_ = 'row-fluid').find('h2').find_next_sibling('h2').get_text()
face = chapter_soup.find('div',class_ = 'span4 pmemoji').find('h1').get_text()
conclusion = chapter_soup.find('h1',class_ = 'review').get_text()
print city.encode('utf-8')
cur.execute('insert into t_pm values(\''+city.encode('utf-8')
            +'\',\''+province.encode('utf-8')
            +'\',\''+pmNum.encode('utf-8')
            +'\',\''+suggest.encode('utf-8')
            +'\',\''+rand.encode('utf-8')
            +'\',\''+conclusion.encode('utf-8')+'\')')


當(dāng)前名稱:創(chuàng)新互聯(lián)Python教程:python向數(shù)據(jù)庫(kù)insert亂碼怎么解決?
文章分享:http://www.dlmjj.cn/article/dphspph.html