Home > Database > Mysql Tutorial > How to Import UTF-8 Encoded Text into MySQL Tables Using Python?

How to Import UTF-8 Encoded Text into MySQL Tables Using Python?

DDD
Release: 2024-10-30 11:56:02
Original
913 people have browsed it

How to Import UTF-8 Encoded Text into MySQL Tables Using Python?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template