python向mysql中插入数据时出现_mysql_exceptions.OperationalError: 1366 Incorrect string value,,python向mysql


python向mysql中插入数据时出现了_mysql_exceptions.OperationalError: (1366, "Incorrect string value: '\xE4\xB8 ......' for column 'pageSnapshot' at row 1")的异常

  File "E:/outofmemory/svn/web/models/minipage/__init__.py", line 356, in addPageVersion    newVersionId = db.insert(self.table_src_page_version,**pageVersion)  File "C:\Python27\lib\site-packages\web.py-0.36-py2.7.egg\web\db.py", line 774, in insert    self._db_execute(db_cursor, q1)  File "C:\Python27\lib\site-packages\web.py-0.36-py2.7.egg\web\db.py", line 587, in _db_execute    out = cur.execute(query, params)  File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 174, in execute    self.errorhandler(self, exc, value)  File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler    raise errorclass, errorvalue_mysql_exceptions.OperationalError: (1366, "Incorrect string value: '\\xE4\\xB8 ......' for column 'pageSnapshot' at row 1")

出现这个异常是mysql问题,而非python的问题,这是因为mysql的字段类型是utf-xxx, 而在mysql中这些utf-8数据类型只能存储最多三个字节的字符,而存不了包含四个字节的字符。

有两个办法可以解决此问题:

修改mysql数据表的字段类型为utf8mb4,不过这个类型只有在mysql 5.5之后才可以支持删除4字节的utf8字符,然后再保存

评论关闭