Tom Klino
Tom Klino

Reputation: 2504

Writing hebrew to mySql using JAVA

I have a small Java method that inserts short messages to a MySQL Database. the table's default Collation is utf8_unicode_ci and the java code is:

private void insertMessageToDataBase(String lRoom, String lChatusername,
            String lMessage) {
        try {
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/embeddedChat?" +
                "user=site_access&password=XXXXXXX");
            addMessageToDataBase = con.prepareStatement("INSERT INTO `" + lRoom + "` (username, message, action)" +
                    " VALUES (?,?,'message');");
            addMessageToDataBase.setString(1, lChatusername);
            addMessageToDataBase.setString(2, lMessage);
            addMessageToDataBase.executeUpdate();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }

the problem is that when lMessage is in hebrew the result is a string of '??????'

BTW: I don't know if it helps but there is also a PHP script that sometimes write to another similar table in this database and it works fine.

Upvotes: 0

Views: 1202

Answers (2)

Tom Klino
Tom Klino

Reputation: 2504

Thank you Marc B for helping me find out what went wrong. This will be just a summery for any future developer who may fall upon a similar issue.

So, from the comment by Marc (above on my question) I understood I needed to check the link. I did not know how to do so but I did a brief google search and came upon this page: http://www.jvmhost.com/articles/tomcat-java-mysql-jdbc-and-unicode

actually all I needed to do was add the following line to the connection string: &useUnicode=true&characterEncoding=UTF-8

this is how my working code looks now:

    private void insertMessageToDataBase(String lRoom, String lChatusername,
            String lMessage) {
        try {
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/embeddedChat?" +
                "user=site_access&password=XXXXXXXX&useUnicode=true&characterEncoding=UTF-8");
            addMessageToDataBase = con.prepareStatement("INSERT INTO `" + lRoom + "` (username, message, action)" +
                    " VALUES (?,?,'message');");
            addMessageToDataBase.setString(1, lChatusername);
            addMessageToDataBase.setString(2, lMessage);
            addMessageToDataBase.executeUpdate();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }

It's a mess of course and needs some clean up, but this is a working code.

Thank you Marc B

Upvotes: 1

Sai Ye Yan Naing Aye
Sai Ye Yan Naing Aye

Reputation: 6738

Set UTF-8 in your code. See this;

    Connection con = DriverManager.getConnection("jdbc:mysql://localhost/embeddedChat?useUnicode=true&characterEncoding=utf8");

Upvotes: 3

Related Questions