在我的程序中,我使用JTDS(http://jtds.sourceforge.net/)连接到Microsoft SQL数据库。我的数据库的编码是iso-8859-1。但是,要使用Java发送查询,我必须使用字符串(通常使用UTF编码)。是否可以使用与UTF不同的编码发送查询?
编辑:使用INSERT或UPDATE后,结果显示错误。如果我只从数据库中选择,则会显示正确的特殊字符。
答案 0 :(得分:2)
java的一个优秀设计原则是text,String,始终是Unicode。一般来说,你甚至看不到它是用Unicode的,因为只有在获取字节时你(应该)指出字节应该被转换成的编码。 所以你不需要做任何事情 - 理想情况下。
错误可能源于:
javac
的编码。 可以通过尝试\u00FC
而不是ü
来测试。 尝试INSERT“\ u00FC +ü”和SELECT进行字节比较。转储字节代码。 (避免控制台问题。)
Arrays.toString(string.getBytes("ISO-8859-1"));
不 尝试修复new String(s.getBytes("ISO-8859-1"), "UTF-8")
- 等等。
如果没有发现任何问题,必须在其他地方寻找原因。
BTW:更好地使用Windows-1252(Windows Latin-1)而不是ISO-8859(Latin-1),因为它允许一些特殊的字符,如逗号般的引号(范围0x80 - 0xBF)。 HTML接受Windows-1252作为 也是ISO-8859-1。答案 1 :(得分:1)
JDBC驱动程序实际上在内部处理转换,如果 只是通过连接字符串来创建插入:
(这很糟糕,从不这样做)
String aValue = "äöü";
String insert = "INSERT INTO table VALUES('" + aValue + "')";
Statement s = connection.createStatement();
s.executeUpdate(insert);
使用预准备语句(这也避免了SQL注入等安全漏洞):
String aValue = "äöü";
String insert = "INSERT INTO table VALUES(?)";
PreparedStatement s = connection.prepareStatement(insert);
s.setString(1, aValue);
s.executeUpdate();
编辑:还要确保您要插入的内容确实是您要插入的内容。对于德国变音符号,在unicode中有多个可能的表示,例如ö可以表示为“\ u00F6”,但它也可以(很少,取决于来源)使用组合变音符号来表示(例如“o \ u0308”也看起来像ö)。
答案 2 :(得分:0)
当我连接到使用ISO-8859-1 I编码的Access数据库(.mdb)时 使用以下语法:
String dbPath = "fakeDBPath.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + dbPath + ";DriverID=22;READONLY=false}";
final Properties prop = new Properties();
prop.put("charSet", "ISO-8859-1");
Connection conn = DriverManager.getConnection( database, prop );
获得连接后,我可以使用Java字符串而无需指定任何其他编码。 也许JTDS支持设置编码的特定属性。
例如,要在数据库中插入数据:
String cmd = "INSERT INTO Table (Col1,Col2,Col3,Col4) VALUES (1000,'àèìòù','é®þü','fake data');";
Statement s = DBTable_1.getStatement();
try
{
int r = s.executeUpdate(cmd);
} catch ( SQLException ex )
{
Logger.getLogger( Main.class.getName() ).log( Level.SEVERE, null, ex );
}
从DB中读取:
String cmd = "SELECT * FROM Table WHERE Col2='àèìòù';";
Statement s = DBTable_1.getStatement();
try
{
ResultSet r = s.executeQuery(cmd);
while(r.next())
{
System.out.println("Col2: " + r.getString(2) + " Col3:" + r.getString(3));
}
} catch ( SQLException ex )
{
Logger.getLogger( Main.class.getName() ).log( Level.SEVERE, null, ex );
}