如何使用jdbc-odbc驱动程序从MS Access数据库正确返回特殊的西班牙语字符 [英] How to correctly return special Spanish characters from a MS Access db with jdbc-odbc driver
问题描述
如何使用MS Acess数据库的jdbc-odbc驱动程序从Ms访问(.accdb或.mdb)数据库返回特殊字符?
How can you return special characters from a Ms access (.accdb or .mdb) database using the jdbc-odbc driver for MS Acess databases?
从结果集的字节(bytes[] bt = rs.getbytes(index_of_field)
然后是new String (bt, "UTF-8")
甚至是new String (bt, "iso-8859-1")
)的字节中进行转换,或者获取字符串(rs.getString()
)都将不起作用,您需要一种有效的方法来执行此操作.
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.
推荐答案
获取特殊字符的方式,例如(某些其他特殊字符也可能会成功返回,但是尚未对此情况进行分析):
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;
}
然后,您只需要将每个字段的值作为字符串返回(请记住将字符串保存在aux变量中,以防多次使用,因为您只需运行rs.getString()
一次):
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
这篇关于如何使用jdbc-odbc驱动程序从MS Access数据库正确返回特殊的西班牙语字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!