首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >mysql和python的编码问题

问mysql和python的编码问题
EN

Stack Overflow用户
提问于 2014-06-20 10:37:07
回答 1查看 27关注 0票数 0

我有python代码,可以从更大的学校中提取数据并将其存储在我们的服务器上。所有的东西都运行的很好,直到它命中了α字符。我用UTF-8对数据库进行了编码,代码将上面的字符存储为: xc1。

代码语言:javascript
复制
import schoolslib, MySQLdb

cities = schoolslib.getcitylist("ca")

for city in cities:
schools = schoolslib.getschoolstest(city)
data = ['gsId', 'name', 'type', 'gradeRange', 'enrollment', 'gsRating', 'parentRating', 'city', 'state', 'districtId', 'district', 'districtNCESId', 'address', 'phone', 'fax', 'website', 'ncesId', 'lat', 'lon', 'overviewLink', 'ratingsLink', 'reviewsLink', 'schoolStatsLink']
db = MySQLdb.connect(host="localhost", user="schools", passwd="", db="schoolinfo")
cursor = db.cursor()
schooldata = [0]*23
for school in schools.iter('school'):
    for x in range(0, 23):
        schooldata[x] = school.find(data[x])
        if (schooldata[x] == None) or (schooldata[x].text == None) :
            schooldata[x] = ""
        else:
            schooldata[x] = schooldata[x].text
            schooldata[x] = schooldata[x].encode('utf-8', "ignore")

    cursor.execute("INSERT INTO school (gsId,name,type,gradeRange,enrollment,gsRating,parentRating,city,state,districtId,district,districtNCESId,address,phone,fax,website,ncesId,lat,lon,overviewLink,ratingsLink,reviewsLink,schoolStatsLink) VALUES %r;" % (tuple(schooldata),))
db.commit()

XML文件:安尼莫·英格尔伍德特许高中

EN

回答 1

Stack Overflow用户

发布于 2014-06-20 11:19:04

当您将()连接到数据库时,在建立MySQL连接时指定字符集和use_unicode参数。

代码语言:javascript
复制
db = MySQLdb.connect(host="localhost", 
                     user="schools", 
                     passwd="", 
                     db="schoolinfo",
                     charset = "utf8",
                     use_unicode =True)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24319119

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档