论坛首页· 友情链接申请·申请版主· 广告投放· 道具中心· 设为首页· 收藏本站
发新话题
打印

MySQL中文解决方案

MySQL中文解决方案

前几天将数据库移到了MySQL上,转移过程中发现MySQL5.0已经改进了很多。真是不用不知道,一用吓一跳啊!不过MySQL的中文问题还是搞得人很头大,不过最终我们还是总结出了一个比较好的解决方案。
一、Web服务器采用resin操作系统采用Windows系列,连接数据库使用数据源方式。在resin/conf/resin.conf中加入如下代码(位于<caucho.com></caucho.com>之间)
<resource-ref>
  <res-ref-name>jdbc/test</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <init-param driver-name="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource"/>
  <init-param url="jdbc:mysql://127.0.0.1:3306/test"/>
  <init-param user="root"/>
  <init-param password=""/>
  <init-param useUnicode="true"/>
  <init-param max-c/>
  <init-param max-idle-time="30"/>
</resource-ref>
注:相关参数请自行改变

二、在连接数据库时使用如下代码建立连接:
        Context env = new InitialContext();
        DataSource pool = (DataSource) env.lookup("java:comp/env/jdbc/erms");
        if (pool == null)
           throw new Exception("jdbc/erms is an unknown DataSource");
        conn = pool.getConnection();
        stmt = conn.createStatement();


三、编写如下两个静态方法:
public static String getstr(String str)
{
      try {
        String temp_p = str;
        byte[] temp_t = temp_p.getBytes("ISO8859-1");
        String temp = new String(temp_t);
        return temp;
      }
      catch (UnsupportedEncodingException ex) {
       System.out.println(ex);
       return "";
      }

}
public static String ISOConverter(String str)
{
       if(str==null)
      {
              str="";
      }
      else{
             try{
                  str=new String(str.getBytes("GBK"),"ISO8859_1");
             }
             catch(Exception ex){
                  ex.printStackTrace();
            }
       }
       return str;
}

        
在执行一个sql语句前,对将要执行的sql语句执行ISOConverter(sql)方法,可以将中文正常的写入MySQL(MySQL中存的是中文,可以使用第三方工具查看);而从数据库中取出数据后,对中文数据字符串使用getstr(cnString)方法,即可得到正确中文的字符串。

需要注意的是,MySQL不需要进行其他任何设置。而除了以上指出的两处需要转换字符编码,没有其他需要转换字符编码的地方了。
        MySQL5.0以及相应JDBC可在http://dev.mysql.com/downloads下载
好好学习,天天向上!

TOP

发新话题