Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to retrieve Data in correct encoding from Mysql using JDBC

when I insert data (includes French characters) to my database using the sql insert into it works fine :

   CREATE TABLE Categories(code_interne_c varchar(100) primary key,
                           description    varchar(100));

   INSERT INTO Categories  VALUES ('01','Matières premières');
   INSERT INTO Categories  VALUES ('02','Articles de conditionnement');
   INSERT INTO Categories  VALUES ('03','Consommables production');
   INSERT INTO Categories  VALUES ('04','Produits de nettoyage');
   INSERT INTO Categories  VALUES ('05','Réactifs');

when I use mysql command line it works fine( as you see its the normal and the expected output) too:

   mysql> select * from categories;
   +----------------+-------------------------------------------+
   | code_interne_c | description                               |
   +----------------+-------------------------------------------+
   | 01             | Matières premières                        |
   | 02             | Articles de conditionnement               |
   | 03             | Consommables production                   |
   | 04             | Produits de nettoyage                     |
   | 05             | Réactifs                                  |
   +----------------+-------------------------------------------+
   14 rows in set (0.00 sec)

but when I retrieve Data using jdbc :

public static String testreqchar(){
    try {
        Statement st = cx.createStatement();
        ResultSet rs = st.executeQuery("select * from categories");
        rs.next();
        return rs.getString(2)+"|| and  test French accent characters : é ô ê à è û ";
    } catch (SQLException ex) {
        Logger.getLogger(Methodes.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}
public static void main(String a[]) {

           System.out.println(testreqchar());
}

this is what i get as an output in my IDE and Interfaces :

    MatiŠres premiŠres|| and  test French accent characters : é ô ê à è û

I don't know what is the problem.

   Mysql 5.5.27 set on UTF-8 as charset on Win server 2008 R2 French
   mysql-connector-java-5.1.21
   JDK 1.7 Running on win 7 pro French.
like image 932
Jalal Sordo Avatar asked Dec 05 '25 23:12

Jalal Sordo


1 Answers

Put useUnicode=true&characterEncoding=UTF8 at the end of your connection String. see sample,

      Connection conn = DriverManager.getConnection  
        ( "jdbc:mysql://localhost/bug_utf8?useUnicode=true&characterEncoding=UTF8"  
like image 83
Sai Ye Yan Naing Aye Avatar answered Dec 07 '25 11:12

Sai Ye Yan Naing Aye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!