Home  >  Article  >  Database  >  How to solve the problem of garbled characters when interacting with Excel and MySQL

How to solve the problem of garbled characters when interacting with Excel and MySQL

PHPz
PHPzOriginal
2023-04-20 10:10:491136browse

When using Excel and MySQL for data interaction, you may encounter the problem of Chinese garbled characters. This article will introduce possible causes of garbled characters and provide some solutions.

1. Reasons

1. Inconsistent character sets: Excel’s default character set is GB2312, while MySQL’s default character set is UTF-8 or GBK, which may cause data to be lost during transmission. Garbled characters appear.

2. Data type mismatch: VARCHAR and TEXT type fields in MySQL can store different character sets, while cells in Excel only support one character set. If Excel cells contain different character sets, garbled characters may appear.

3. Inconsistent file encoding: When using Excel to open or save files in CSV format, encoding inconsistencies may occur. For example, if ANSI encoding is selected when saving a CSV file, and MySQL uses UTF-8 encoding, the data may be garbled during transmission.

2. Solution

1. Consistent character set: Setting the character set to GB2312 when connecting to MySQL can avoid garbled characters caused by inconsistent character sets. For example, you can add the following parameters in MySQL Connector/ODBC:

charset=GB2312

2. Data type matching: When creating a MySQL data table, you can specify fields of VARCHAR and TEXT types. It is the GB2312 character set. For example:

CREATE TABLE test (
id INT NOT NULL,
name VARCHAR(30) CHARACTER SET GB2312 DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

3. Consistent file encoding: When using Excel to save CSV files, UTF-8 encoding should be selected to ensure consistent file encoding. For example, click "File" -> "Save As" in Excel and select the "CSV UTF-8 (comma-delimited)" format.

In addition, sometimes you can also use the SET NAMES command to set the character set in MySQL. For example:

SET NAMES 'GB2312';

In short, if you encounter garbled code problems during data interaction, you need to carefully check the data type, character set and file encoding to determine the problem. where and take appropriate solutions.

The above is the detailed content of How to solve the problem of garbled characters when interacting with Excel and MySQL. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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