Importing UTF-8 Encoded Text into MySQL Tables Using Python
Subsequently, when attempting to load the data via LOAD DATA LOCAL INFILE, users may encounter the distortion of non-English characters. To address this, it is essential to encode the data prior to import.
Encoding UTF-8 Data in Python
To encode the data in UTF-8 using Python, the codecs module can be employed. The following code snippet demonstrates the encoding process:
<code class="python">import codecs with open('data.csv', 'rb') as f: data = f.read().decode('utf-8')</code>
Loading Encoded Data into MySQL
Once the data has been encoded, it can be loaded into the MySQL table using the LOAD DATA LOCAL INFILE command with the following modifications:
<code class="sql">LOAD DATA INFILE 'data.csv' IGNORE INTO TABLE table CHARACTER SET UTF8 FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n'</code>
By incorporating these modifications, the data will be successfully loaded into the MySQL table, preserving the integrity of the non-English characters.
The above is the detailed content of How to Import UTF-8 Encoded Text into MySQL Tables Using Python?. For more information, please follow other related articles on the PHP Chinese website!