ivaneeo's blog

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

            BlogJava :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
            669 Posts :: 0 Stories :: 64 Comments :: 0 Trackbacks
          首先創(chuàng)建表,我們這里默認編碼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;


          這里創(chuàng)建表類型時要使用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 閱讀(648) 評論(0)  編輯  收藏 所屬分類: ruby-寶石也鋒芒
          主站蜘蛛池模板: 商洛市| 牙克石市| 桂阳县| 涿鹿县| 扬州市| 墨江| 镇巴县| 读书| 龙山县| 镇沅| 绥棱县| 吴桥县| 襄汾县| 陵川县| 汤阴县| 赞皇县| 佛冈县| 金乡县| 赤水市| 都安| 芷江| 禄劝| 舞阳县| 松滋市| 苏尼特右旗| 名山县| 桂平市| 桐乡市| 定襄县| 河曲县| 拉孜县| 鄂托克旗| 芦山县| 迭部县| 泰州市| 安陆市| 阿勒泰市| 会同县| 察雅县| 富阳市| 金阳县|