Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to insert utf-8 chars with prepared statement to mysql

Tags:

java

mysql

I have problem insert utf-8 chars with preparred statement like this:

    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/tournament_system?"
            + "user=root&password=root");

    java.sql.PreparedStatement ps = conn
            .prepareStatement("  insert into PLAYER (ID, NAME, SURNAME, CLUB,  WORLD_RANKING, USER_ID)  VALUES(?, ?, ?, ?,  ?, ?)");
    ps.setInt(1, 100001);
    ps.setString(2, "ěščřž");
    ps.setString(3, "xxx");
    ps.setString(4, null);
    ps.setInt(5, 5);
    ps.setInt(6, 1);
    ps.executeUpdate();

it insert into column name just this: "?š??ž"

but when I execute sql in phpMyAdmin like this:

INSERT INTO `tournament_system`.`PLAYER` (`ID`, `NAME`, `SURNAME`, `CLUB`, `PLAYER_DISCRIMINATOR`, `WORLD_RANKING`, `USER_ID`) VALUES ('10002', 'ěščřž', 'qqq', NULL, 'qqq', NULL, '1');

it works good

so where is the problem ? I think I have configured my db right if second option works

MYSQL Version:

Server: Localhost via UNIX socket
Server version: 5.5.34-0ubuntu0.12.10.1
Protocol version: 10
User: root@localhost
MySQL charset: UTF-8 Unicode (utf8)

UPDATED:

when I tried this: ps.setBytes(2, "ččřž".getBytes("UTF-8")); then it works but I really cant change all my ps to this. How to solve it otherwise ?

like image 330
hudi Avatar asked Jan 25 '26 05:01

hudi


1 Answers

You can add the encoding to your jdbc connection string with characterEncoding=UTF-8, which will take effect on the PreparedStatement:

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/tournament_system?"
        + "user=root&password=root&characterEncoding=UTF-8");
like image 131
influjensbahr Avatar answered Jan 26 '26 17:01

influjensbahr