python - python脚本中的mysql编码问题

标签 python mysql

我之前发布过此内容,但仍然遇到问题。我在数据库中得到错误的输出,问题是当脚本存储此条目“Á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/

相关文章:

python - Django:用元组过滤组合列

java - 转换用于 mysql 数据库的 java long unix 时间戳

mysql - 如何忽略wait_timeout/interactive_timeout?

python - Flask 和长时间运行的任务

python - 如何通过对 (r,c) 数据帧的每个元素执行函数来创建 (r,c,n) 数组? (Python)

python - 将 Python REST API 调用转换为 Power Query

mysql - 如何将条件内部查询转换为 MYSQL 中的 LEFT JOIN?

mysql - INSERT 查询未在 MySQL 存储过程中运行

mysql - 如何在 MySQL 数据库中存储电话号码?

python - 需要安装PyOpenGL(Windows)