用pymysql向數據庫中插入數據報錯

問題:用pymysql向數據庫中插入數據報錯

備註:數據庫表格有時候默認字符編碼爲latin-1:

錯誤一:

UnicodeEncodeError: 'latin-1' codec can't encode characters in position 133-145: ordinal not in range(256)

原因:數據與數據庫中字符編碼不相同

解決方法:pymysql.connect()中添加charset='utf8mb4'

# Connect to the database:連接數據庫

            self.connection = pymysql.connect(host=host,

                                              port=int(port),

                                              user=user,

                                              password=password,

                                              db=db,

                                              charset='utf8mb4',

                                              cursorclass=pymysql.cursors.DictCursor)

錯誤二:

InternalError: (pymysql.err.InternalError) (1366, "Incorrect string value: '\\xE6\\xAD

原因:pymysql內部錯誤,插入的數據數據庫表格編碼格式不支持

解決方法:

運行命令  mysql> alter table 表名 convert to character set utf8mb4;

錯誤三:

'latin-1' codec can't encode characters in position 32-34: ordinal not in range(256)

原因:不能識別輸入的中文

解決方法:value = value.encode("utf-8").decode("latin1")  #value是你輸入的中文

備註:MySQL在5.5.3之後增加了這個utf8mb4的編碼,mb4就是most bytes 4的意思,專門用來兼容四字節的unicode。好在utf8mb4是utf8的超集,除了將編碼改爲utf8mb4外不需要做其他轉換。當然,爲了節省空間,一般情況下使用utf8也就夠了。可以簡單的理解 utf8mb4 是目前最大的一個字符編碼,支持任意文字。

參考鏈接:mysql字符集 utf8 和utf8mb4 的區別

參考鏈接:https://blog.csdn.net/sinat_41721615/java/article/details/94979429

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章