How to correctly return special Spanish characters

2019-07-25 18:37发布

问题:

How can you return special characters from a Ms access (.accdb or .mdb) database using the jdbc-odbc driver for MS Acess databases?

Converting from bytes of the result set(bytes[] bt = rs.getbytes(index_of_field) and then new String (bt, "UTF-8") or even new String (bt, "iso-8859-1")) or getting the string (rs.getString()) won't work and you need a valid way to do it.

回答1:

The way to get special characters like (some other special characters may also be returned successfully, however, that case hasn't been analyzed yet):

  • Á,É,Í,Ó,Ú,á,é,í,ó,ú,Ü,ü,Ñ,ñ

and format all the returned string correctly (I mean the queried fields) the following procedure must be followed.

Before the connection to the DB is donde, and before querying the database, we must define a property parameter like the charset:

Properties props;

props = new Properties();
props.put ("charSet", "iso-8859-1");

Then we need to add props to the database connection. In the end, this is the final code you need.

String dbPath = "C:/example/directory/myDatabase.accdb";


Properties props;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String connURL="jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+dbPath;

try {

    props = new Properties();
    props.put ("charSet", "iso-8859-1");

    con = DriverManager.getConnection(connURL, props);
    stmt = con.createStatement();
    stmt.execute("select "field+" from "+tableName); // query exec

    rs = stmt.getResultSet(); // query resultset
    rsMetaData = rs.getMetaData(); // resultset metadata

} catch (SQLException ex) {

    return false;
}

Then you just need to return the value of each field as a string (remember to save the string in an aux variable, in case you want to use it more than once, since you can just run rs.getString() once):

String resultString;

if( rs != null){

  while( rs.next() ){  // this while may be surrounded with a try-catch
    // Fields will be displayed for every row in the DB
    // indexField must start from 1 !

    for (int indexField = 1; indexField<=rsMetaData.getColumnCount(); indexField++){

      resultString = rs.getString(field_index);
      System.out.println(This is the field of column number "+indexField+": "+resultString);

    } // for close
  } // while close
} // if close