首先創建表,我們這里默認編碼utf8:
create table samples (
????id int not null auto_increment,
????foo varchar(100) not null,
????bar text not null,
????primary key (id)
) Type=MyISAM CHARACTER SET utf8;
這里創建表類型時要使用MyISAM類型,因為只有MyISAM類型才支持完整的utf8.最后設置編碼utf8.
1.dbi操作數據庫
如果你本地編碼時gbk的話,首先要默認類Iconv進行轉換.
require 'iconv'
def gb2u str
conv = Iconv.new("UTF-8", "GBK")
str = conv.iconv(str)
str << conv.iconv(nil)
conv.close
str
end
插入代碼:
DBI.connect('DBI:Mysql:test:localhost', 'mysql', '') { |dbh|
dbh.execute 'SET NAMES utf8' #這里要指明代碼
1.upto(13) { |i|
st.execute("insert into samples(foo, bar) values('#{gb2u('一')}#{i}', '#{gb2u('二')}')")
}
}
2.activerecord
activerecord是對dbi的包裝.(也更神,呵呵!)
代碼:
require 'rubygems'
require_gem 'activerecord' #因為我是gem的安裝
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:database => "test",
:username => "mysql",
:password => "",
:encoding => "utf8") #編碼只需這里指明
#指明表
class Mytab < ActiveRecord::Base
set_table_name 'samples'
end
#插入數據
tab = Mytab.new
tab.foo= gb2u('一')
tab.bar = gb2u('二')
tab.save
#查詢數據
data = Mytab.find(:all)
data.each { |line|
puts "['#{line[:id]}', '#{line[:foo]}, '#{line[:bar]}]"
}