UTF-8 Encoding Issue with Java and MySQL
When working with Java and MySQL, it's essential to ensure proper UTF-8 encoding to avoid character storage issues. Here's how to resolve a common problem where special characters are stored as question marks in the database:
Problem:
Using the createStatement method and executing SQL queries involving special characters results in characters being stored as question marks. For example, extended characters like "מסירות קצרות" may appear as "???????".
Answer:
The issue originates from missing Unicode and character encoding parameters when establishing the connection with MySQL. To resolve this, add the following parameters when creating the connection:
<code class="java">con = DriverManager.getConnection("jdbc:mysql:///dbname?useUnicode=true&characterEncoding=utf-8", "user", "pass");</code>
This ensures that the connection uses Unicode encoding and the specified charset (in this case, UTF-8) for character representation. By setting these parameters, MySQL can correctly handle and store special characters.
Additional Tips:
The above is the detailed content of How to Fix UTF-8 Encoding Issues when Using Java and MySQL?. For more information, please follow other related articles on the PHP Chinese website!