Home  >  Article  >  Database  >  Why Are My UTF-8 Strings Displaying As Corrupted Characters When Inserting Into MySQL Using JDBC?

Why Are My UTF-8 Strings Displaying As Corrupted Characters When Inserting Into MySQL Using JDBC?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 18:03:02145browse

Why Are My UTF-8 Strings Displaying As Corrupted Characters When Inserting Into MySQL Using JDBC?

How to Properly Insert UTF-8 Strings into MySQL via JDBC

Problem Statement:

When inserting UTF-8 strings into a MySQL database using the JDBC interface, the characters are displaying as corrupted or unreadable symbols.

Expected String: Апарати
Actual Result: ???????

Initial Troubleshooting:

<code class="java">Class.forName("com.mysql.jdbc.Driver").newInstance();
String dbPath = String.format(
    "jdbc:mysql://%s:%d/%s?user=%s&amp;password=%s&amp;characterEncoding=utf-8&amp;&quot; + 
    "&amp;useUnicode=true", ci.host, ci.port, ci.dbName, ci.user, ci.password);
conn = java.sql.DriverManager.getConnection(dbPath);</code>

Additional Troubleshooting:

These steps were taken additionally:

  • Added lines suggested by Costis Aivalis to /etc/mysql/my.cnf.
  • Removed the following lines from the code:

    <code class="java">query = "set character set utf8";
    stat.execute(query);</code>

Solution:

It appeared that the source of discrepancy between Java code and the MySQL table data was due to character set inconsistencies. The issue was resolved when the character set settings in the Java code were removed.

Comparing the MySQL command used in the Java code to the analogous command from the command prompt, a subtle difference was discovered:

<code class="java">String query = "insert into clt" + " (id, text) values (?, ?)";</code>
<code class="bash">mysql> insert into clt (id, text) values (12656697, "Апарати");</code>

In the Java code, the character set utf8 suffix was omitted from the create table statement This divergence between the Java code and the direct MySQL command creates the mismatch in character-set handling.

Conclusion:

When inserting UTF-8 strings into MySQL using the JDBC interface, it is essential to ensure the character set settings are consistent between the Java code and the database configuration. This ensures that strings are correctly handled and stored in the database.

The above is the detailed content of Why Are My UTF-8 Strings Displaying As Corrupted Characters When Inserting Into MySQL Using 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