Domanda

I am trying to make an application that connects to an Access database. I have made it through making the ODBC connection of my Java program with an .mdb file but I have this problem with Unicode characters. If a record is written in English (Latin) characters then the .mdb file recognizes the characters but if the record is written in Greek then some weird characters appear and I can't get the record with the ResultSet object. Can someone help?

È stato utile?

Soluzione

The JDBC-ODBC Bridge will not work correctly with the Access ODBC driver when strings contain Unicode characters whose code point is above U+007F. Greek characters fall into that category, so the JDBC-ODBC Bridge approach will not work for you. (More details here.) Also, the JDBC-ODBC Bridge has been removed from Java (since Java 8).

To get proper support for Greek characters I would recommend using UCanAccess. For an overview of how to set that up, see another of my answers here.

Once your project has been configured to use UCanAccess you can work with your Access database using code like this:

Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/unicode.accdb");
String language = "Greek";

PreparedStatement ps = conn.prepareStatement(
        "SELECT [word], [english_equiv] " +
        "FROM [vocabulary] " +
        "WHERE language=?");
ps.setString(1, language);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
    System.out.println(String.format(
            "\"%s\" is %s for \"%s\".", 
            rs.getString("word"),
            language,
            rs.getString("english_equiv")));
}
rs.close();
ps.close();

String newWord = "ηλεκτρονικός υπολογιστής";
String newEnglishEquiv = "computer";
ps = conn.prepareStatement(
        "INSERT INTO [vocabulary] ([word], [language], [english_equiv]) " +
        "VALUES (?,?,?)");
ps.setString(1, newWord);
ps.setString(2, language);
ps.setString(3, newEnglishEquiv);
ps.executeUpdate();
System.out.println(String.format(
        "\"%s\" has been added to the table.", 
        newWord));

That code produces the following console output:

"γιορτή" is Greek for "feast"
"ηλεκτρονικός υπολογιστής" has been added to the table.

(Translations courtesy of Google Translate.)

Altri suggerimenti

If you call ResultSet.first() or ResultSet.last(), you have to properly initialize Statement or PreparedStatement:

PreparedStatement ps =conn.prepareStatement("SELECT *  FROM T1",ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);

@Gord, thanks for all you are doing about UCanAccess.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top