我之前发布了这篇文章,但我仍然有问题。我在数据库中得到了错误的输出问题是,当脚本存储这个条目时,它显示的是"xc3x81nimo Inglewood Charter“。我正在打印控制台中的值,并且它显示正确。我在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()发布于 2014-07-07 13:36:11
要将值传递到数据库,请使用?占位符,并让execute为您引用值。不要使用Python的%或str.format函数,因为Python不如数据库游标智能。
cursor.execute("update employee set manager=? where empid=?", (mgrid,empid))(这显示了update,但insert使用相同的样式。)
https://stackoverflow.com/questions/24603426
复制相似问题