Saturday, September 4, 2010

Testing sequel to access SQLite

require 'rubygems'
require 'sequel'

class SequelTest

  def initialize
    # @db = Sequle.connect("sqlite:test2.db") # this does not create database
    @db = Sequel.sqlite("test2.db")
    unless(@db.table_exists?(:table1))
      @db.create_table :table1 do
        primary_key :id
        String :title
      end
    end
  
    unless(record_exists?(:table1, :title, 'test1'))
      @db[:table1].insert(:title => 'test1')
    end
  
    unless(record_exists?(:table1, :title, 'test2'))
      @db[:table1].insert(:title => 'test2')
    end
  
    unless(record_exists?(:table1, :title, 'test3'))
      @db[:table1].insert(:title => 'test3')
    end
  
  end

  def record_exists?(table, field, value)
    rows = @db[table].where(field => value)
    return (rows.count>0)
  end
  
  def show_all
    p "Database type:" + @db.database_type.to_s
    @db.fetch('select * from table1') do |row|
      p row
    end
  end

end

app = SequelTest.new
app.show_all

$ ruby seq01sq.rb 
"Database type:sqlite"
{:title=>"test1", :id=>1}
{:title=>"test2", :id=>2}
{:title=>"test3", :id=>3}

No comments:

Post a Comment