新手问题 Ruby 访问 MySQL 字符编码问题

realsatan · 2015年11月11日 · 最后由 msg7086 回复于 2015年12月01日 · 2258 次阅读

正在学 Active Record,需要从 PHP 访问的数据库中读取中文字段,遇到乱码。

经过测试,发现数据库中正常的 UTF8 编码数据不能正确读入到 Ruby 中。


在 MySQL 命令行中,分别用两种编码插入“中文”,PHP 也是使用 UTF8 的方式:

SET NAMES Latin1;
insert into users value(1, "中文", "none");

SET NAMES UTF8;
insert into users value(2, "中文", "none");

结果(Latin1):

结果(UTF8):

在 Ruby(Active Record)中,只能直接读取 Latin1 编码,UTF8 为乱码。

使用 gem mysql 来直接查表:

my = Mysql.real_connect("**")
res1 = my.query("select * from users;")
res1.each do |r|
  p r
end

结果: ["1", "\xE4\xB8\xAD\xE6\x96\x87", "none"] ["2", "??", "none"]

增加 SET NAMES

my.query("set names utf8")
res2 = my.query("select * from users;")
res2.each do |r|
  p r
end

结果: ["1", "\xC3\xA4\xC2\xB8\xC2\xAD\xC3\xA6\xE2\x80\x93\xE2\x80\xA1", "none"] ["2", "\xE4\xB8\xAD\xE6\x96\x87", "none"]

用 SET NAMES 能解决 Ruby 读取 MySQL 中文的问题,但是使用 Active Record 没有这个步骤,请问解决方法。

应该是写在 database.yml 中的:

development:
  adapter: mysql
  encoding: unicode
  ...

谢谢楼上,刚试了下,在配置文件中加入这行成功了:encoding: utf8

encoding: unicode 的情况下,报错: Character set 'unicode' is not a compiled character set and is not specified in the '/usr/share/mysql/charsets/Index.xml'

估计我们的环境有点不同,我的是 Debian 6,MySQL 5.1,ruby 2.2.3

悲情的发现,以前写了编码配置,但是单词错了: encode: utf8 ,encoding 该是名词吧。

#2 楼 @realsatan MySQL 5.1,,,,,你们 PHPer 都是从外星来的?

#3 楼 @hooopo Debian 下用 apt-get 安装的,这个 Debian 的发行版确实很老了。开源的 CMS 支持就好,其实不懂 PHP 的。

Debian 6 也太老了点,我都已经在用 9 beta 了,就算是 stable 也应该用 8 了。

#5 楼 @msg7086 三年前阿里云买的服务器,有运行的服务怕升级出问题。

#6 楼 @realsatan 这时候就需要 staging server 试运行。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号