3

我正在将Sinatra应用程序从 SQLite3 切换到 MySQL。出于某种我无法理解的原因,当我使用 Ruby 和Sequel从 MySQL 中提取数据时,字符出现在 8 位 ASCII 而不是 UTF-8 中。

部署环境是 FreeBSD 9.1 和 MySQL 5.6.12,从 FreeBSD 端口安装了系统范围的 ruby​​19。不过,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?
4

1 回答 1

4

尝试使用mysql2适配器而不是mysql适配器,因为我相信mysql2驱动程序处理编码而mysql驱动程序不处理。

于 2013-07-10T16:12:57.453 回答