Python3 error 'latin-1' codec can't encode character solution

Python3 error 'latin-1' codec can't encode character solution

When updating the database operation, an error is reported:

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

After Baidu, I got three solutions, of which I personally think the third is the most convenient.

1. Handling strings

code omitted

2. Set the database encoding

One way is to set when connecting to the database

db.set_charset('utf-8')
cursor.execute('SET NAMES utf8;')
cursor.execute('SET CHARACTER SET utf8;')
cursor.execute('SET character_set_connection=utf8;')

However, it didn't work for me after using this method.

Another way to set the database encoding is to change the configuration file.
  • Can be encoded by db.set_charset('utf-8')querying the database

  • windows change database encoding

1. Find the my.ini file in the mysql installation directory (if not, copy my-medium.ini, and then rename it to my.ini). In mysql5.7, it is the my-default file.

2. Find the [client] and [mysqld] fields in the my.ini file, add default-character-set=utf8 below, save and close

3. Restart the mysql service

  • Linux change database encoding

  • Under mysql version 5.5

  1. Open the configuration file, my configuration file is in /etc/mysql/my.cnf
  2. Add default-character-set=utf8 under both [client] and [mysqld] fields, save and close
  3. restart mysql service
  • MySQL version 5.5 and above
  1. Open the configuration file, my configuration file is in /etc/mysql/my.cnf

  2. Add under [mysqld]:

    character-set-server=utf8

    collation-server=utf8_general_ci

  3. restart mysql service

  • After setting the code successfully

3. Set parameters when connecting to the database

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

Set use_unicode and charset parameters

Reference blog:
https://blog.csdn.net/wanglingxxx/article/details/52049278

https://blog.csdn.net/u010663668/article/details/54881998

https://blog.csdn.net/shuifa2008/article/details/9254389

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325261979&siteId=291194637