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&password=%s&characterEncoding=utf-8&" + "&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:
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!