close

ruby with sqlite3

#!/usr/bin/ruby -Ku
# encoding: utf-8
require 'amalgalite'
require 'fileutils'

class String
    @@tmp_db = "tmp_db.txt"
    @@gsp_db = "gsp_corpus.db"
    @@gsp_corpus = "gsp_corpus" #table name                                            @@field_name = "word source"
  def to_db #字串與資料庫查詢
    FileUtils.rm(@@tmp_db) if File.exist?(@@tmp_db)  # start with a clean slate    
    my_db=Amalgalite::Database.new(@@gsp_db)
    stmt = my_db.execute("select * from gsp_corpus where word = ?", "#{self}")
    my_db.close

    if stmt.any?
      File.open("./#{@@tmp_db}","a") do |txt|
               txt.puts stmt.join(',')
      end
      res = File.open("./#{@@tmp_db}").read
      return res
    end
  end #end to_db

  def save_to_db
    str = self.gsub(/,/,"\",\"").gsub(/^/,"\"").gsub(/$/,"\"")
    my_db=Amalgalite::Database.new(@@gsp_db)
    stmt = my_db.execute("select * from gsp_corpus where word = ?", "#{self.split(',')[0]}")
  if !(stmt.any?)
   insert_stmt = "insert into gsp_corpus (%s) values (%s)" % [@@field_name.split.join(','), str]
   my_db.execute(insert_stmt)
   puts "insert into sqlite3_db sucessfully"
  end
    my_db.close


  end
end #end class





arrow
arrow
    全站熱搜

    igogo 發表在 痞客邦 留言(0) 人氣()