ivaneeo's blog

自由的力量,自由的生活。

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  669 Posts :: 0 Stories :: 64 Comments :: 0 Trackbacks
首先创建表,我们这里默认编码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]}]"
}




posted on 2006-11-20 14:28 ivaneeo 阅读(628) 评论(0)  编辑  收藏 所属分类: ruby-宝石也锋芒

只有注册用户登录后才能发表评论。


网站导航: