MySQLdb FAQ

1. The solution to garbled characters in MYSQLdb in Python

Generally speaking, the most troublesome problem in using mysql is garbled characters.

Check the encoding of mysql:

show variables like 'character_set_%';

You can see the following results:

character_set_client is the encoding method of the client;
character_set_connection is the encoding used to establish the connection; the encoding of the
character_set_database database; the encoding of the
character_set_results result set; the encoding of the
character_set_server database server;

As long as the above four encoding methods are the same, there will be no garbled characters .

Then you can set the encoding of mysql directly here.

set character_set_client = xxxxx

In this way, the client code is modified.

However, for the established databases and data tables, the encoding has not changed, and the alter command should be used to change the corresponding encoding .

However, even if the encoding of the database is modified, there will still be garbled characters when storing in the database in python. The solution is to specify the encoding when linking to the database . E.g:

sql_con = MySQLdb.connect(host=MYSQL_ADDR , user=MYSQL_USER , passwd=MYSQL_PWD , db=MYSQL_DB , charset="utf8")

This specifies that the encoding of the client is utf8. Then the problem of garbled characters is solved.

 

Guess you like

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