python 向MySQL里插入中文数据

用python向MySQL中插入中文数据出错,原代码片段:

复制代码
1 db = MySQLdb.connect("localhost","root","123","TESTDB")
2 cursor = db.cursor()
3 sql = '''INSERT INTO aaaa(bb,cc) values(%s , %s)''' 
4 
5 data = ("山东","威海")
6 cursor.execute(sql,data)
7 
8 conn.commit()
9 conn.close()
复制代码

运行提示:

UnicodeEncodeError: 'latin-1' codec can't encode character u'\u674e' in position 0: ordinal not in range(256)

解决方案:

db = MySQLdb.connect("localhost","root","123","TESTDB",use_unicode=1, charset='utf8')

 

 
 
posted @ 2014-10-17 13:53  不过是海i  阅读(160)  评论(0编辑  收藏  举报