服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java 中文问题的解决 mysql, oracle, servlet, jsp


  java 中文问题一直困扰许多学习者。总结了下面的一些情况的解决方法。
  希望对大家有帮助。
  连接 mysql database server:
  -------------------------------------------------------------------------------
   mysql 不支持 unicode,所以比较麻烦。
   将 connectionstring 设置成 encoding 为 gb2312
   string connectionstring
   = "jdbc:mysql://localhost/test?useunicode=true&characterencoding=gb2312";
  
  测试代码:
   string str = "汉字";
   preparedstatement pstmt = conn.preparestatement("insert into test values (?)");
   pstmt.setstring(1,str);
   pstmt.executeupdate();
  
  数据库表格:
   create table test (
   name char(10)
   )
  
  
  连接 oracle database server
  -------------------------------------------------------------------------------
   在把汉字字符串插入数据库前做如下转换操作:
   string(str.getbytes("iso8859_1"),"gb2312")
  
  测试代码:
   string str = "汉字";
   preparedstatement pstmt = conn.preparestatement("insert into test values (?)");
   pstmt.setstring(1,new string(str.getbytes("iso8859_1"),"gb2312");
   pstmt.executeupdate();
  
  
  servlet
  -------------------------------------------------------------------------------
   在 servlet 开头加上两句话:
   response.setcontenttype("text/html;charset=utf-8");
   request.setcharacterencoding("utf-8");
  
  jsp
  -------------------------------------------------------------------------------
   在 jsp 开头加上:
   <%@ page contenttype="text/html; charset=gb2312" %>

扫描关注微信公众号