您的位置:首页 > 编程语言 > Python开发

python3 pymysql 'latin-1' codec can't encode character 错误 问题解决

2018-03-06 16:35 1391 查看
完整代码:

#coding: utf-8

import pymysql

# 打开数据库连接

db = pymysql.connect("localhost","root","00000000","TESTDB" ,use_unicode=True, charset="utf8")

# 若没有 use_unicode=True, charset="utf8" 那么就会发生如题错误:



# 使用cursor()方法获取操作游标 

cursor = db.cursor()

# SQL 插入语句

sql = """INSERT INTO EMPLOYEE(FIRST_NAME,

         LAST_NAME, AGE, SEX, INCOME)

         VALUES ('测', '试', 20, '男', 99999)"""

#db.set_character_set('utf8')

cursor.execute('SET NAMES utf8;') 

cursor.execute('SET CHARACTER SET utf8;')

cursor.execute('SET character_set_connection=utf8;')

try:

    # 执行sql语句

    cursor.execute(sql)

    # 提交到数据库执行

    db.commit()

    print(" 没有错误 请党和组织人民放心! ")

   

except Exception as e:

    print(e)

    # 如果发生错误则回滚

    print(" 发生错误")

    db.rollback()

# 关闭数据库连接

db.close()

执行结果如下:



问题原因:

pymysql 正常情况下会尝试将所有的内容转为latin1字符集处理

解决思路:

设置连接和游标的charset为你所希望的编码,如utf8

参考网站:
http://stackoverflow.com/questions/3942888/unicodeencodeerror-latin-1-codec-cant-encode-character
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐