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')