LiangShuang's ...

I'm not a programmer...

MySQL 中文显示乱码~~~

shuang posted @ 2011年1月02日 05:34 in MySQL with tags mysql utf-8 , 4083 阅读

    最近学习MySQL时又遇到了一个烦人的问题,中文编码,虽然在建立数据库时设置的字符编码为utf8,在MySQL的console上执行insert插入中文时没问题,可是在java代码中插入中文到mysql中就是??了,就是代码中的realName

	 /************************************************************
	 * Add resident
	 ************************************************************
	 */
	public boolean addResident(String userID,String realName,String gender,
			String birth,String addr,String tel,String email,String checkin) {
		Connection conn = this.getConnection();
		CallableStatement stmt = null;
		Date birthDate = null;
		Date checkinDate = null;
		if(birth!=null && (!birth.equals(""))) {
			birthDate = Date.valueOf(birth);
		}
		if(checkin!=null && (!checkin.equals(""))) {
			checkinDate = Date.valueOf(checkin);
		}
		try {
			stmt = conn.prepareCall("{call ICommunity.addResident(?,?,?,?,?,?,?,?,?)}");
			stmt.setString(1, userID);
			stmt.setString(2, realName);
			stmt.setString(3, gender);
			stmt.setDate(4, birthDate);
			stmt.setString(5, addr);
			stmt.setString(6, tel);
			stmt.setString(7, email);
			stmt.setDate(8, checkinDate);
			
			stmt.registerOutParameter(9, Types.BOOLEAN);
			stmt.execute();
			return stmt.getBoolean(9);
			
			
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		finally {
			try {
				conn.close();
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

差了好多资料,可还是没有解决根本问题,不管在代码里怎么改变字符编码,到数据库中显示的还是乱码

String name = null;
try {
        //name = realName.getBytes("UTF-8").toString();
        name = new String(realName.getBytes("iso_8859_1"),"utf8");
    } catch (UnsupportedEncodingException e) {
	// TODO Auto-generated catch block
	System.out.println("Exception "+e.getMessage());
}

最后一篇很给力的文章解决了问题:http://developer.51cto.com/art/200906/130425.htm,需要设置一下mysql的配置文件中的client和server的默认编码。

在linux下这个配置文件在/etc/mysql/my.cnf,编辑之后的文件内容为:

[client]
port        = 3306
socket      = /var/run/mysqld/mysqld.sock
default-character-set=utf8
# Here is entries for some specific programs
# The following values assume you have at least 32M ram

# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket      = /var/run/mysqld/mysqld.sock
nice        = 0

[mysqld]
#
# * Basic Settings
#

default-character-set=utf8

就是分别在[client]和[mysqld]下添加设置默认编码的语句。

然后重启mysql,sudo /etc/init.d/mysql restart

结果就正常了。。。

还有一篇介绍字符编码的文章也很给力:http://www.regexlab.com/zh/encoding.htm


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter