首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python脚本中的mysql编码问题

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

Stack Overflow用户
提问于 2014-07-07 13:15:26
回答 1查看 16关注 0票数 0

我之前发布了这篇文章,但我仍然有问题。我在数据库中得到了错误的输出问题是,当脚本存储这个条目时,它显示的是"xc3x81nimo Inglewood Charter“。我正在打印控制台中的值,并且它显示正确。我在mysql数据库中使用排序规则utf8_unicode_ci,下面是我的代码:

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

发布于 2014-07-07 13:36:11

要将值传递到数据库,请使用?占位符,并让execute为您引用值。不要使用Python的%或str.format函数,因为Python不如数据库游标智能。

代码语言:javascript
复制
cursor.execute("update employee set manager=? where empid=?", (mgrid,empid))

(这显示了update,但insert使用相同的样式。)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24603426

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档