Home  >  Article  >  Database  >  How to Ensure Correct UTF-8 String Insertion into MySQL through JDBC?

How to Ensure Correct UTF-8 String Insertion into MySQL through JDBC?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 15:27:29304browse

How to Ensure Correct UTF-8 String Insertion into MySQL through JDBC?

How to Correctly Write UTF-8 Strings into MySQL through JDBC Interface

Problem:

While attempting to insert UTF-8 strings into a MySQL database using the JDBC interface, the data is being displayed incorrectly in the database.

Background:

The code snippet provided demonstrates the process of connecting to a database, creating a table, inserting rows with UTF-8 data, and checking the inserted data. However, the output shows that the UTF-8 characters are being corrupted.

Troubleshooting:

1. Verify MySQL Configuration Encoding:

Ensure that the MySQL configuration file (my.cnf or my.ini) contains the correct character encoding settings. Check the settings with the following commands:

show variables like 'character%';

show variables like 'collation%';

2. Modify Configuration File (if necessary):

Based on your MySQL version, add the following lines to the configuration file:

[mysqld]
character-set-server = utf8
character-set-filesystem = utf8

OR

[client]
default-character-set=utf8

[mysql]
default-character-set=utf8

[mysqld]
default-character-set=utf8
character-set-server=utf8

3. Configure JDBC Connection:

When establishing the JDBC connection, specify the following parameter:

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase?useUnicode=true&characterEncoding=UTF-8","user","passwd");

4. Remove Redundant Code:

Based on the provided code snippet, it is recommended to remove the following lines from the code:

query = "set character set utf8";
stat.execute(query);

Expected Outcome:

After implementing these changes, the UTF-8 strings should be correctly written and displayed in the MySQL database.

The above is the detailed content of How to Ensure Correct UTF-8 String Insertion into MySQL through JDBC?. 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