I believe that the visitor here has read a lot of configuration file setting methods. But the problem persists. This article will record in detail my solution.
My environment: mysql5.6 + python2.7.3 + MySQLdb1.2.4
1. Right-click the computer on the desktop, select "manage", select "services and applications"> "services", and find the MySQL56 service in it.
2. Right-click MySQL service and check "properties". drag it back and find the "-default-file" text box. The configuration file to be loaded when MySQL is started is specified here.
3. Find the configuration file in the path and modify it.
4. Specific modification content:
Text:
[Client]
Port = 3306
Default-character-set = utf8mb4
[Mysql]
Port = 3306
Default-character-set = utf8mb4
[Mysqld]
Port = 3306
Character-set-client-handshake = FALSE
Character-set-server = utf8mb4
Collation-server = utf8mb4_unicode_ci
Init_connect = 'set NAMES utf8mb4'
5. Restart the MySQL 56 service.
6. In the running process, locate and open mysql command line and run the following command to check whether the command takes effect.
Showvariables where Variable_name LIKE 'character \ _ set \ _ % 'OR Variable_name LIKE 'collation % ';
The following figure shows that it takes effect:
7. Do you think this is the end? No. Even in this case, whether in mysql workbench or the utf8mb4 database established through python + mysqldb, it is still UTF-8. Because of this, our emoj characters cannot be inserted into the database.
Even if the created database is utf8mb4, we can see that the database is still utf8.
Therefore, we still need to continue the experiment. Take a closer look at the modified configuration file: init_connect = 'setnames utf8mb4 ', so I can use it in the database.
Indeed, after the "set names utf8mb4;" sentence was added, the database became utf8mb4 .:
In this way, the application can be promoted to the code. See 8.
8. Applicable to python + mysqldb or python + sqlalchemy.
After the connection is created, the cursor object must first execute "set names utf8mb4;" to ensure that the database connection is in utf8mb4 encoding format, and the database will become utf8mb4. The content above is paved. If there are no 8th steps, the content above is made in white.
Mysql:
Sqlalchemy: