我之前发布过此内容,但仍然遇到问题。我在数据库中得到错误的输出,问题是当脚本存储此条目“Ánimo Inglewood Charter High School”时,它显示“xc3x81nimo Inglewood Charter High School”。我正在控制台中打印这些值并且它显示正确。我在 mysql 数据库中使用排序规则 utf8_unicode_ci 这是我的代码:
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", charset = "utf8", use_unicode =True)
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('utf8', "ignore")
print schooldata[x]
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()
最佳答案
要将值传递到数据库,请使用 ?
占位符,并让 execute
为您引用这些值。不要使用 Python 的 %
或 str.format
函数,因为 Python 不像数据库游标那么智能。
cursor.execute("update employee set manager=? where empid=?", (mgrid,empid))
(这显示更新
,但插入
使用相同的样式。)
关于python - python脚本中的mysql编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24603426/