Home > Database > Mysql Tutorial > How to Load UTF-8 Encoded Text into MySQL Tables Without Garbled Characters?

How to Load UTF-8 Encoded Text into MySQL Tables Without Garbled Characters?

DDD
Release: 2024-10-29 04:38:02
Original
731 people have browsed it

 How to Load UTF-8 Encoded Text into MySQL Tables Without Garbled Characters?

Loading UTF-8 Encoded Text into MySQL Tables

When importing data into MySQL tables containing non-English characters encoded in UTF-8, users may encounter issues with garbled characters despite setting the table's column character set to UTF-8.

To address this, it is necessary to ensure proper encoding of the data before loading it into the table. In Python, using the LOAD DATA LOCAL INFILE command to load a UTF-8 encoded CSV file requires including the CHARACTER SET UTF8 clause.

The following code snippet demonstrates how to load UTF-8 encoded data into a MySQL table using Python:

<code class="python">import mysql.connector

# Establish connection to MySQL
conn = mysql.connector.connect(...)

# Execute LOAD DATA query
query = "LOAD DATA INFILE 'file.csv' IGNORE INTO TABLE table CHARACTER SET UTF8 FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n'"
cursor = conn.cursor()
cursor.execute(query)
cursor.close()

# Commit changes
conn.commit()</code>
Copy after login

By following these steps, users can successfully load UTF-8 encoded data into MySQL tables and preserve the non-English characters in their original form.

The above is the detailed content of How to Load UTF-8 Encoded Text into MySQL Tables Without Garbled Characters?. 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