1.问题:在windows环境下使用PyCharm时,我想向mysql的一张表中插入数据,代码如下
import MySQLdb
from scrapy.conf import settings
class XiaoHuar_Pipeline(object):
def process_item(self, item, spider):
host = settings['MYSQL_HOST']
user = settings['MYSQL_USER']
psd = settings['MYSQL_PASSWORD']
db = settings['MYSQL_DB']
port = settings['MYSQL_PORT']
charset = settings['CHARSET']
con = MySQLdb.connect(host=host,user=user,passwd=psd,db=db,port=port)
cue = con.cursor()
print "mysql connect successfully"
sql = "insert into girl(name,school,pic) values('{0}','{1}','{2}')".format(item['name'],item['school'],item['pic'])
cue.execute(sql)
con.commit()
con.close()
return item
由于插入的数据中有中文,mysql中出现了乱码
2.原因:考虑到我的数据库编码是utf-8
于是我在连接数据库时,加入charset='utf-8',结果出现错误
con = MySQLdb.connect(host=host,user=user,passwd=psd,db=db,port=port,charset='utf-8')
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\twisted\internet\defer.py", line 653, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "D:\PyWorkspace\p1\p1\pipelines.py", line 17, in process_item
con = MySQLdb.connect(host=host,user=user,passwd=psd,db=db,port=port,charset='utf-8')
File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 215, in __init__
self.set_character_set(charset)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 294, in set_character_set
super(Connection, self).set_character_set(charset)
OperationalError: (2019, "Can't initialize character set utf-8 (path: c:\\Program Files\\MySQL\\MySQL Server 5.1\\\\share\\charsets\\)")
通过google之后发现,原来python2中使用的是'utf8'而不是'utf-8',于是对代码进行修改
con = MySQLdb.connect(host=host,user=user,passwd=psd,db=db,port=port,charset='utf8')
更改之后,中文就可以正常插入数据库了。