我正在尝试mysql
使用mysql
/ mysqlplus
ruby gems 获取数据。这是代码:
$ cat 1.rb
#!/home/yuri/.rvm/wrappers/ruby-1.9.3-p385@test/ruby
require 'mysql'
db = Mysql.init
db.options Mysql::SET_CHARSET_NAME, 'utf8'
db = Mysql.real_connect 'localhost', 'root', 'password'
db.select_db 'site'
db.query "SET NAMES utf8"
res = db.query 'SELECT * FROM users LIMIT 1'
p res.fetch_hash['non_latin_field'].encoding
p db.character_set_name
$ ./1.rb
#<Encoding:ASCII-8BIT>
"latin1"
也是如此mysqlplus
。预期结果如下:
$ ./1.rb
#<Encoding:UTF-8>
"utf8"
我做错了吗?
UPD
澄清事项:
$ mysql --help | grep ^default-character-set
default-character-set utf8
$ mysql -u root -p -BNe "SHOW VARIABLES LIKE 'character_set\_%'"
Enter password:
character_set_client utf8
character_set_connection utf8
character_set_database utf8
character_set_filesystem binary
character_set_results utf8
character_set_server utf8
character_set_system utf8
$ mysql -u root -p -e "CREATE DATABASE d1 CHARACTER SET = utf8"
Enter password:
$ mysql -u root -p -e "CREATE TABLE t1 (f1 VARCHAR(255) CHARACTER SET utf8)" d1
Enter password:
$ mysql -u root -p -e "INSERT INTO t1 (f1) VALUE ('уключина')" d1
Enter password:
$ cat 1.php
#!/usr/bin/env php
<?php
$args = array_slice($_SERVER['argv'], 1);
mysql_connect('localhost', 'root', '...');
mysql_select_db('d1');
$r = mysql_query('SELECT f1 FROM t1');
echo mysql_fetch_assoc($r)['f1'];
$ ./1.php
уключина
$ cat 1.rb
#!/home/yuri/.rvm/wrappers/ruby-1.9.3-p385@test/ruby
require 'mysql'
db = Mysql.new 'localhost', 'root', 'fdfnfh'
if ARGV.include? '--explicit'
db.query "SET NAMES utf8"
end
db.select_db 'd1'
f1 = db.query('SELECT * FROM t1 LIMIT 1').fetch_hash['f1']
if ARGV.include? '--force-encoding'
f1.force_encoding 'utf-8'
end
p f1
db.query("SHOW VARIABLES LIKE 'character_set\\_%'").each do |row|
p row
end
$ ./1.rb
"????????"
["character_set_client", "latin1"]
["character_set_connection", "latin1"]
["character_set_database", "utf8"]
["character_set_filesystem", "binary"]
["character_set_results", "latin1"]
["character_set_server", "utf8"]
["character_set_system", "utf8"]
$ ./1.rb --explicit
"\xD1\x83\xD0\xBA\xD0\xBB\xD1\x8E\xD1\x87\xD0\xB8\xD0\xBD\xD0\xB0"
["character_set_client", "utf8"]
["character_set_connection", "utf8"]
["character_set_database", "utf8"]
["character_set_filesystem", "binary"]
["character_set_results", "utf8"]
["character_set_server", "utf8"]
["character_set_system", "utf8"]
$ ./1.rb --explicit --force-encoding
"уключина"
["character_set_client", "utf8"]
["character_set_connection", "utf8"]
["character_set_database", "utf8"]
["character_set_filesystem", "binary"]
["character_set_results", "utf8"]
["character_set_server", "utf8"]
["character_set_system", "utf8"]
所以问题显然不在于mysql
,而在于如何让这些gem使用编码以外的方式ASCII-8BIT
。