mysql中文问题

环境:Hibernate 2.1.7 + MySQL4.1(MySQL的编码已设置为utf8)
问题:通过Hibernate向MySQL写入中文后,通过Hibernate取回数据,在console中打印java对象显示正常。但在MySQL Query Browser中看到的是乱码,传给前端的Flex也是乱码。
原因:Hibernate的基础还是JDBC,所以一样需要设置characterEncoding!
解决方法
在hibernate.cfg.xml中应该这样写

<property name="connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8</property>

如果用hibernate.properties
#hibernate.connection.url jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8

ps:处理中文的话,characterEncoding用GBK一样可以。
但字节编码问题最好的解决方法还是统一使用UTF-8!!!

从MySQL 4.1开始引入的多语言支持确实很棒,而且一些特性已经超过了其他的数据库系统。不过我在测试过程中发现使用适用于MySQL 4.1之前的PHP语句操作MySQL数据库会造成乱码,即使是设置过了表字符集也是如此。我读了一下新的MySQL在线手册中第十章”Character Set Support“后终于找到了解决方法并测试通过。

MySQL 4.1的字符集支持(Character Set Support)有两个方面:字符集(Character set)和排序方式(Collation)。对于字符集的支持细化到四个层次: 服务器(server),数据库(database),数据表(table)和连接(connection)。

当我们按照原来的方式通过PHP存取MySQL数据库时,就算设置了表的默认字符集为utf8并且通过UTF-8编码发送查询,你会发现存入数据库的仍然是乱码。问题就出在这个connection连接层上。解决方法是在发送查询前执行一下下面这句:

SET NAMES ‘utf8′;

CREATE DATABASE `bbscs7`
    CHARACTER SET 'utf8'
    COLLATE 'utf8_general_ci';

CREATE TABLE `bbscs_agreeagainst` (
  `ID` varchar(40) NOT NULL default '',
  `UserID` varchar(40) NOT NULL default '',
  `PostID` varchar(40) NOT NULL default '',
  `BoardID` bigint(20) NOT NULL default '0',
  `VoteType` tinyint(1) default '0',
  `CreateTime` bigint(20) NOT NULL default '0',
  PRIMARY KEY  (`ID`),
  UNIQUE KEY `id` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

如果和hibernate组合使用:

加入一个帮助类:

public class Sinogram
{
    /**
     * sinogram
     */
    private static Sinogram sinogram = null;

    /**
     * 私有构造,防止新建实例
     */
    private Sinogram()
    {
        super();
    }

    /**
     * 获取实例,单实例模式!
     *
     * @return Sinogram
     * @throws Exception
     */
    public static Sinogram getInstance()
    {
        if(null == sinogram)
        {
            sinogram = new Sinogram();
        }
        return sinogram;
    }

    /**
     * 中文编码转换
     *
     * @param str String
     * @return String
     */
    public String toGBK(String str)
    {
        if(str != null)
        {
            try
            {
                str = new String(str.getBytes("ISO8859-1"));
            }
            catch(Exception e)
            {
                System.err.println("toGBK Exception:" + e.getMessage());
                System.err.println("The String is:" + str);
            }
        }
        return str;
    }
}

然后向下面这样插入数据:

personInfo.setName(Sinogram.getInstance().toGBK(theForm.getName()));

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值