javamysqlcharacter-encodingwampserverturkish

Writing Turkish characters to MySQL using WampServer and Java


i am having a problem with my Wamp Server. When i execute a query which contains Turkish characters, i am getting this error:

SEVERE: Incorrect string value: '\xE7l? ya...' for column 'body' at row 1
java.sql.SQLException: Incorrect string value: '\xE7l? ya...' for column 'body' at row 1

Here is my Java code:

Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
PreparedStatement p = con.prepareStatement("SET NAMES utf8");
p.executeUpdate();
PreparedStatement ps = 
        con.prepareStatement("INSERT INTO duyurular values (?, ?, ?, ?)");
ps.setInt(1, 0);
ps.setString(2, title);
ps.setString(3, body);
ps.setInt(4, writer);
ps.executeUpdate();

My database and table which i am trying to write to are all set to "utf8_turkish_ci" collation. My Wamp Server version is 2.2.

table

table structure

I am able to write Turkish characters using PHPMyAdmin sql console but not able to with my Java code. What should i do to get over this? Thanks in advance.


Solution

  • There is nothing in here that would tell the driver to encode strings in UTF-8. You are only making the database expect UTF-8, and then the driver encodes your strings in some other encoding and the database throws an error.

    You don't show what your url is, but it's supposed to be like this:

    jdbc:mysql:///dbname?useUnicode=true&characterEncoding=utf-8
    

    Then you can remove this:

    PreparedStatement p = con.prepareStatement("SET NAMES utf8");
    p.executeUpdate();