ruby&sqlite的例子

来源:互联网 发布:去香港用什么网络 编辑:程序博客网 时间:2024/06/03 00:37

例子1

require 'sqlite'db = SQLite::Database.new( "test.db" )sql = <<SQL  drop table the_table;  create table the_table (    a varchar2(30),    b varchar2(30)  );  insert into the_table values ( 'one', 'two' );  insert into the_table values ( 'three', 'four' );  insert into the_table values ( 'five', 'six' );SQLdb.execute_batch( sql )db.results_as_hash = truedb.execute( "select * from the_table" ) do |row|  print row['a'], ',  ', row['b']  putsend


例子2

require 'sqlite'require 'net/http'def accessNet(stat, url)  res = Net::HTTP.get(URI.parse(URI.escape(url)))  res.gsub(/<[^>]*>/m, ' ').gsub(/[\r\n]/m, ' ').gsub(/'/m, '"').scan(/([a-zA-Z-]+)\s/).each do |v|    v = v.to_s.downcase    stat[v] = (stat[v]==nil) ? 1 : stat[v]+1  endenddef saveData(db, stat)  sql, i = '', 0  stat.each do |k, v|    i = i+1    sql = "#{sql}insert into the_table values ('#{k}', #{v});"    if(i%1000==0)      db.transaction do |db|         db.execute_batch( sql )      end      sql=''    end  end  db.transaction do |db|     db.execute_batch( sql ) if(sql!='')  endenddef doinit(db)    sql = <<SQL      drop table the_table;      create table the_table (        key varchar(300),        val int      );SQL    db.execute_batch( sql )enddef printInfo(db)    # do the select    db.results_as_hash = true    db.execute( "select * from the_table t order by t.val desc" ) do |row|      puts "#{row[0]}, #{row[1]}"    end    rows = db.execute( "select count(*) from the_table" )    p rowsenddb = SQLite::Database.new( "test.db" )doinit dbstat = {}accessNet(stat, 'http://www.chinadaily.com.cn/world/2011-08/12/content_13102444.htm')accessNet(stat, 'http://www.chinadaily.com.cn/world/2011-08/12/content_13099183.htm')accessNet(stat, 'http://www.chinadaily.com.cn/world/2011-08/13/content_13106532.htm')accessNet(stat, 'http://www.chinadaily.com.cn/world/2011-08/14/content_13107273.htm')accessNet(stat, 'http://www.chinadaily.com.cn/world/2011-08/12/content_13099653.htm')accessNet(stat, 'http://www.chinadaily.com.cn/world/2011-08/14/content_13107262.htm')accessNet(stat, 'http://www.chinadaily.com.cn/world/2011-08/15/content_13110160.htm')saveData db, statprintInfo db


相关的软件下载:

sqlite : http://www.sqlite.org/sqlitedll-2_8_17.zip

ruby gem : http://rubyforge.org/frs/?group_id=254&release_id=1522

原创粉丝点击