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 databasewindows 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
- Open the configuration file, my configuration file is in /etc/mysql/my.cnf
- Add default-character-set=utf8 under both [client] and [mysqld] fields, save and close
- restart mysql service
- MySQL version 5.5 and above
Open the configuration file, my configuration file is in /etc/mysql/my.cnf
Add under [mysqld]:
character-set-server=utf8
collation-server=utf8_general_ci
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