Skip to content
Advertisement

Can’t insert Cyrillic symbols into MySQL with JDBC

I have a web app which uses com.mysql.jdbc.Driver to connect to MySQL database. Here are jdbcMySQL.properties:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/dbname?characterEncoding=UTF-8
jdbc.username=....
jdbc.password=....

my.cnf has these settings:

[client]
port            = 3306
socket          = /var/run/mysqld/mysqld.sock
default-character-set = utf8

[mysqld_safe]
socket          = /var/run/mysqld/mysqld.sock
nice            = 0

[mysqld]
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql
default-character-set = utf8
skip-external-locking

I create database like this:

CREATE DATABASE dbname CHARACTER SET utf8 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT COLLATE utf8_general_ci;

CREATE TABLE tblname (
    `login` VARCHAR(50) NOT NULL,
    `description` TEXT
) DEFAULT CHARACTER SET utf8 COLLATE=utf8_general_ci ROW_FORMAT=DYNAMIC;

And the problem is: if I make

insert into tblname (login, description) VALUES ('qwe', 'йцукен');

then I have in my table

| qwe |  йцукен |

BUT, if I make:

jdbcTemplate.update("INSERT INTO work_time (login, date_time) VALUES (?, ?);", 
    new PreparedStatementSetter() {
    @Override
    public void setValues(PreparedStatement ps) throws SQLException {
          ps.setString(1, "qwe");
          ps.setString(4, "йцукен");
       }
    }
);

I have in my table:

qwe | ??????

Advertisement

Answer

MySQL is a bit crazy w.r.t. encodings, try:

jdbc.url=jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=utf-8

Furthermore there is one more possible error cause: check that the editor encoding is the same as the javac compiler encoding. If they differ you see something different than what is compiled.

You could try the u-escaped version to test that, or look in the project settings:

"u0439u0446u0432u043au0435u043d"
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement