I posted this previously but I'm still having issues. I get the wrong output in the database the issue is when the script stores this entry "Ánimo Inglewood Charter High School" it shows "xc3x81nimo Inglewood Charter High School" instead. I am printing the values in the console and it shows properly. I am using collation utf8_unicode_ci in the mysql database here is my code:
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()
To pass values to the database, use the ?
placeholder, and let execute
quote the values for you. Don't use Python's %
or str.format
functions, because Python isn't as smart as the database cursor.
cursor.execute("update employee set manager=? where empid=?", (mgrid,empid))
(This shows update
, but insert
uses the same style.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.