Ruby和MySQL UTF-8字符

我正在将Sinatra应用程序从sqlite3切换到MysqL.由于某些我无法理解的原因,当我使用Ruby和SequelMysqL提取数据时,字符以8-BIT ASCII而不是UTF-8出现.

部署环境是FreeBSD 9.1和MysqL 5.6.12,从FreeBSD端口安装了系统范围的ruby19. RVM ruby​​-2.0p247产生相同的结果.

我的my.cnf是以下内容

# The following options will be passed to all MysqL clients
[client]
default-character-set=utf8
#password = your_password
port    = 3306
socket    = /tmp/MysqL.sock
# Here follows entries for some specific programs

# The MysqL server
[MysqLd]
port    = 3306
socket    = /tmp/MysqL.sock
skip-external-locking
key_buffer_size = 128M 
max_allowed_packet = 1M
table_open_cache = 256
sort_buffer_size = 1M
read_buffer_size = 1M
read_rnd_buffer_size = 2M
myisam_sort_buffer_size = 32M
thread_cache_size = 4
query_cache_size= 8M 
# Try number of cpu's*2 for thread_concurrency
thread_concurrency = 2

# encoding issues
character-set-server=utf8
collation-server=utf8_general_ci

log-bin=MysqL-bin
binlog_format=mixed
server-id = 1
[MysqLdump]
quick
max_allowed_packet = 16M

[MysqL]
no-auto-rehash
safe-updates

[myisamchk]
key_buffer_size = 64M
sort_buffer_size = 64M
read_buffer = 1M
write_buffer = 1M

[MysqLhotcopy]
interactive-timeout

我所有的文件都使用shebang行以及UTF-8编码,例如我用来测试条目的以下脚本:

#!/usr/bin/env ruby
# encoding: UTF-8

require 'sequel'

msql = Sequel.connect(adapter: 'MysqL', host: 'localhost', database: 'metrosignage', user: 'atma', password: 'toola697', encoding: 'utf8')

b = msql[:drama_addressbook]
b.each do |entry|
  p entry
  # p entry[:city].force_encoding("utf-8")
end

如果我使用entry [:city] .force_encoding(“ utf-8”)输出是正确的,希腊UTF-8字符将显示正常.但是我不明白为什么我不能直接提取UTF-8.

我正在读取数据的表是使用以下sql创建的:

CREATE TABLE `drama_addressbook` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  `address_no` int(11) DEFAULT NULL,
  `address_description` varchar(255) DEFAULT NULL,
  `phone` varchar(255) DEFAULT NULL,
  `city` varchar(255) DEFAULT NULL,
  `country` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8;

因此,数据库为UTF-8,数据为UTF-8.我的问题是:

>我做错什么了吗?
> Ruby为什么需要force_encoding?

解决方法:

尝试使用MysqL2适配器而不是MysqL适配器,因为我相信MysqL2驱动程序会处理编码,而MysqL驱动程序则不会.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...