Java编程中中文乱码的问题


http://blog.csdn.net/wonder4/archive/2007/06/26/1667158.aspx


String sql2 = "select * from test2";
   ResultSet rs = connDB.executeQuery(sql2);
   rs.previous();

   while (rs.next()) {
    String aa = rs.getString("name");
    System.out.println(aa);
    byte[] gbkiso2 = aa.getBytes("ISO-8859-1");
    String str1422 = new String(gbkiso2, "GBK");
    System.out.println(str1422);
   }
运行,呵,结果出来"呵呵",对着了。

反过来,如果我们要插入中文字符到数据库中
String str = "测试数据";
String sql = "insert into test1(id, name) values(6,'" + str + "')";
conn = getConnection();
stmt = conn.createStatement();
result = stmt.executeUpdate(sql);
插入后数据库中出现的当然会是乱码,
顺着上面查询的逆向思维,开点小猜结果就对了
String str = "测试数据";
byte[] strByte = str.getBytes("gbk");
String str2 = new String(strByte, "ISO-8859-1");
//现在打印出来的str2应该是乱码 ;-)
String sql = "insert into test1(id, name) values(6,'" + str2 + "')";
conn = getConnection();
stmt = conn.createStatement();
result = stmt.executeUpdate(sql);

你可能感兴趣的:(java,sql,编程,.net,Blog)