简体   繁体   中英

How to save special characters in database

I'm using a MySQL database and inserting like this:

  try (Connection connection = DbConnector.connectToDb();
             PreparedStatement stm = connection.prepareStatement("INSERT INTO Country (name) VALUES (?)")) {
            stm.setString(1, name);
            if (stm.executeUpdate() > 0) {
                result = true;
            }
        } catch (Exception e) {
            logStackTrace(e);
        }

Now when I insert: België it is saved in a weird way in the database the ë isn't saved. How can I solve this?

EDIT:

I just changed the table via:

ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

But still when I add a new one it isn't displayed correctly on the webpage.

There is 2 points in the database to check in order to correctly set the UTF-8 charset.

Database Level

This is obtained by creating it :

CREATE DATABASE 'db' CHARACTER SET 'utf8';

Table Level

All of the tables need to be in UTF-8 also (which seems to be the case for you)

CREATE TABLE  `Table1` (
    [...]
) DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;

The important part being DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci

Finally, if your code weren't handling utf8 correctly, you could have forced your JVM to use utf8 encoding by changing the settings by on startup :

java -Dfile.encoding=UTF-8 [...]

or changing the environment variable

"**JAVA_TOOLS_OPTIONS**" to -Dfile.encoding="UTF-8"

or programmatically by using :

System.setProperty("file.encoding" , "UTF-8");

(this last one may not have the desire effect since the JVM caches value of default character encoding on startup)

Hope that helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM