mysql和python的编码问题

2024-05-15 22:47:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有python代码,可以从更大的学校提取数据并将其存储在我们的服务器上。一切都很好,直到它击中角色。我将数据库编码为UTF-8 general,代码将上述字符存储为:xc1

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文件: Á尼莫·英格尔伍德特许高中


Tags: 代码nameincityfordbdatacursor
1条回答
网友
1楼 · 发布于 2024-05-15 22:47:57

将()连接到数据库时,请指定字符集,并在建立MySQL连接时使用\u unicode参数

db = MySQLdb.connect(host="localhost", 
                     user="schools", 
                     passwd="", 
                     db="schoolinfo",
                     charset = "utf8",
                     use_unicode =True)

相关问题 更多 >