![](/img/trans.png)
[英]How do I retrieve a row from a SQLite database through Java's jdbc using a string variable?
[英]Strange encoding in SQLite database: How to retrieve string values with JDBC?
我有
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:cities.db");
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("select * from cities;");+
while (rs.next()) {
byte[] bytes = rs.getBytes("country");
String country = new String(bytes, "utf-8");
System.out.println(country);
}
rs.close();
conn.close();
我的输出显示 表示ä,ö,ü等字符。
如果我从命令行运行sqlite3
并从那里查询表,那么字符很好......
“编译指示编码;” 显示utf-8 ...
如果我调试,字节数组在“ü”的位置有“-127”...
怎么解决这个问题? 什么可能导致这个问题?
链接到示例SQLite文件(只有一行):
你能试试吗?
Class.forName(org.sqlite.JDBC.class.getCanonicalName());
String url = "jdbc:sqlite:";
SQLiteConfig config = new SQLiteConfig();
config.setEncoding(SQLiteConfig.Encoding.UTF8);
Connection conn = DriverManager.getConnection(url, config.toProperties());
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("select * from cities;");+
while (rs.next()) {
String country = rs.getString("country");
System.out.println(country);
}
这里的问题是SQLite数据库包含使用旧的IBM OEM字符集( 代码页437 )编码的字符,因此'ü'字符编码为0x81。 这是Unicode中未使用的字符以及ISO- *和Windows- *字符集的所有(?)。
我能够正确地提取“国家”值
public static void main(String[] args) {
String connectionURL = "jdbc:sqlite:C:/__tmp/cities.db";
try (Connection conn = DriverManager.getConnection(connectionURL)) {
String sql = "SELECT Country FROM CITIES";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String s = new String(rs.getBytes(1), "cp437");
System.out.println(s);
}
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.