python向数据库insert乱码怎么解决?
发布时间:2025-12-29 16:57:34

python对数据库中insert数据的乱码解决方案:
确保以下四个代码都是utf-8:
1. 代码
2. 数据库连接
3. 表格的字符集格式
4. 插入的数据格式
每一步的操作如下:
1. 保证代码的格式是utf-8,这句话加在代码的前面
#-*-coding:utf8-*- #第一个用来确定编码,加上这个句子
2. 确保数据库的连接格式为utf-8
conn=MySQLdb.connect(host='localhost',user='root',passwd='****',db='kfxx',port=3306,charset='utf8') cur=conn.cursor()
3. 保证表的字符集格式为utf-8,建表时可设置

4. 确保插入的数据格式为utf-8,分为utf-8和字符串格式
#解决乱码问题
html___.urlopen(cityURL,timeout=120).read()
mychar=chardet.detect(html_1)
bianma=mychar['encoding']
ifbianma=='utf-8'orbianma=='UTF-8':
html=html_1
else:
html=html_1.decode('gb2312','ignore').encode('utf-8')chapter_soup=BeautifulSoup(html)
city=chapter_soup.find('p',class_='row-fluid').find('h1').get_text()
province=chapter_soup.find('a',class_='province').get_text()
pmNum=chapter_soup.find('p',class_='row-fluid').find('span').get_text()
suggest=chapter_soup.find('p',class_='row-fluid').find('h2').get_text()
rand=chapter_soup.find('p',class_='row-fluid').find('h2').find_next_sibling('h2').get_text()
face=chapter_soup.find('p',class_='span4pmemoji').find('h1').get_text()
conclusion=chapter_soup.find('h1',class_='review').get_text()
printcity.encode('utf-8')
cur.execute('insertintot_pmvalues(\''+city.encode('utf-8')
+'\',\''+province.encode('utf-8')
+'\',\''+pmNum.encode('utf-8')
+'\',\''+suggest.encode('utf-8')
+'\',\''+rand.encode('utf-8')
+'\',\''+conclusion.encode('utf-8')+'\')')更多Python知识请关注Python自学网
