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 閱讀(649) 評論(0)  編輯  收藏 所屬分類: ruby-寶石也鋒芒
          主站蜘蛛池模板: 两当县| 孝感市| 定安县| 多伦县| 河池市| 漠河县| 得荣县| 遂川县| 洪雅县| 和林格尔县| 高雄市| 阿城市| 庆云县| 江油市| 林周县| 永平县| 东安县| 永和县| 卢湾区| 平乡县| 平塘县| 广州市| 樟树市| 邳州市| 区。| 邛崃市| 宣城市| 荥阳市| 海原县| 安丘市| 甘肃省| 蚌埠市| 铜陵市| 安康市| 临城县| 枣强县| 张家港市| 咸丰县| 哈密市| 桦甸市| 丰顺县|